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

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

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

我该如何做这个循环?

最佳答案

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

关于python - 制作一个循环以显示空白表格或预填表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35649793/

相关文章:

python - django 表单,cleaned_data 为空

python - Pandas 数据框 : Fill Missing Months

python - 使用 Python 的正则表达式 : findall inside a boundry

python - 使用 python 将文件上传到 Django 服务器

python - 实现自定义用户模型时 createsuperuser 出现问题

javascript - 使用 AJAX 进行表单验证

__le__、__ge__ 的 python 错误?

python - 为什么将 DatetimeIndex 转换为 np.array 时格式会发生变化?

python - 了解 Django 中的 View 评估

php - 表单未提交到数据库