【问题标题】:Django: How to iterate over form fields choices without knowing the fields name?Django:如何在不知道字段名称的情况下迭代表单字段选择?
【发布时间】:2020-07-26 01:16:36
【问题描述】:

我有一个表单,其字段是在其 __init__ 方法中创建的:

class Form(forms.Form):

    def __init__(self, modelInstance, *args, **kwargs):
        super(Form, self).__init__(*args, **kwargs)
        # create fields based of modelInstance data (because it might change)
        self.fields[modelInstance.name] = models.ChoiceField(choices=SomeChoices, widget=forms.RadioSelect())

因此我无法提前知道如何命名该字段。

现在如何在不知道其名称的情况下迭代字段选择?

我想要什么:

{% for field in form %}
    <p>sometext</p>
      {% for value, text in field.NAME.choices %}
          <input type="radio" name="{{ field.name }}" value="{{value}}" id="id_{{ field.name }}_{{forloop.counter0}}">
          <label>{{text}}</label>
      </div>
      {% endfor %}
{% endfor %}

我知道 field.NAME 只返回实际的字段名称,不让我访问它的选择。但是我还能怎么做呢?

非常感谢任何帮助!

【问题讨论】:

    标签: python django django-forms django-templates


    【解决方案1】:

    【讨论】:

    • 我已经在表单上使用 RadioSelect 作为小部件。文档会像我想要的那样迭代无线电选项,是的,但这只是因为它们明确指定了字段名称('beatles')。自定义模板可能有效,但我不想为这个用例编辑全局模板。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-20
    • 2012-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多