【问题标题】:How to access initial values of form fields in a loop in Django templates如何在 Django 模板中循环访问表单字段的初始值
【发布时间】:2015-01-01 17:00:50
【问题描述】:

我想在模板中显示表单域的初始值。

class MyForm(forms.Form):
    myfield = forms.CharField(max_length=100, initial='test')

当我调用特定字段时,一切都很好,但是当我遍历表单时,什么都没有发生

{% for field in form.fields %}
    {{ field.initial }}            # output: (nothing)
{% endfor %}

{{ form.fields.myfield.initial }}  # output: 'test'

这是预期的行为吗?如何在循环中访问初始值?

【问题讨论】:

    标签: python django django-forms django-templates


    【解决方案1】:

    循环遍历form 本身。

    {% for field in form %}
    

    【讨论】:

      【解决方案2】:

      这应该可行:

      {% for field in form %}
          {{ field.field.initial }}
      {% endfor %}
      

      【讨论】:

        猜你喜欢
        • 2012-11-08
        • 2016-12-24
        • 1970-01-01
        • 1970-01-01
        • 2011-03-13
        • 2013-07-06
        • 1970-01-01
        • 1970-01-01
        • 2015-06-22
        相关资源
        最近更新 更多