制作一个循环以显示空白表格或预填表格

时间:2016-02-26 10:53:13

标签: python django forms django-forms django-templates

我希望在我的数据库中没有答案时,我可以创建一个显示空白表单的循环。

目前我有这段代码:

 <form method="POST" action="">
    {{ formset.management_form }} {% csrf_token %}
    <table>

      {% for question in questions %}<hr>

    <label for="question">{{ question }} [{{ question.id }}]</label>  
    <input type="hidden" id="id_form-{{ forloop.counter0 }}-question" name="form-{{ forloop.counter0 }}-question" value="{{ question.id }}"/>

  </p>

  {% for reply in question.reply_set.all %}
    <p>
    <label for="answer">Réponse :</label>
    <input type="text" id="id_form-{{ forloop.parentloop.counter0 }}-answer" name="form-{{ forloop.parentloop.counter0 }}-answer" value="{{ reply.answer }}"/>
    <input type="hidden" id="id_form-{{ forloop.parentloop.counter0 }}-id" name="form-{{ forloop.parentloop.counter0 }}-id" value="{{ reply.id }}"/>
    </p>
  {% endfor %}

{% endfor %}
 </table>
    <center><input type="submit" value="Submit" class="btn btn-success" />
    <a href="../../baseVisite/" class="btn btn-success">Retour</a></center>
  </form>

此表单允许我更改问题的答案,但如果我的数据库中已有答案... 如果还没有答案,我会做一个循环显示空白表格

我该如何进行此循环?

2 个答案:

答案 0 :(得分:3)

您可以使用for...empty模板标记。

{% for reply in question.reply_set.all %}
    <p>
        <label for="answer">Réponse :</label>
        <input type="text" id="id_form-{{ forloop.parentloop.counter0 }}-answer" name="form-{{ forloop.parentloop.counter0 }}-answer" value="{{ reply.answer }}"/>
        <input type="hidden" id="id_form-{{ forloop.parentloop.counter0 }}-id" name="form-{{ forloop.parentloop.counter0 }}-id" value="{{ reply.id }}"/>
    </p>
{% empty %}

    {# your blank form goes here #}

{% endfor %}

答案 1 :(得分:1)

{% if question.reply_set.all %}
{% for reply in question.reply_set.all %}
<p>
  <label for="answer">Réponse :</label>
  <input type="text" id="id_form-{{ forloop.parentloop.counter0 }}-answer" name="form-{{ forloop.parentloop.counter0 }}-answer" value="{{ reply.answer }}"/>
  <input type="hidden" id="id_form-{{ forloop.parentloop.counter0 }}-id" name="form-{{ forloop.parentloop.counter0 }}-id" value="{{ reply.id }}"/>
</p>
{% endfor %}
{% else %}
<p>
  <label for="answer">Réponse :</label>
  <input type="text" id="id_form-{{ forloop.parentloop.counter0 }}-answer" name="form-{{ forloop.parentloop.counter0 }}-answer"/>
  <input type="hidden" id="id_form-{{ forloop.parentloop.counter0 }}-id" name="form-{{ forloop.parentloop.counter0 }}-id"/>
</p>
{% endif %}

基本上它会检查是否有任何答案,如果它们显示了答案,如果没有,则显示空答案表。