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

Make a loop to display a blank form or pre-filled form

我希望当我的数据库中没有答案时,我可以循环显示空白表格。

目前我有这个代码:

 <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>

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

我该如何做这个循环?

您可以为此使用 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 %}
{% 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 %}

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