与自定义数据相关联的Django动态表单字段

时间:2014-04-30 08:31:14

标签: django django-forms

我希望能够访问传递对象的属性。有可能吗?

我试过这样的事,但它不起作用:(

class SearchResultForm(forms.Form):
    def __init__(self, persons, *args, **kwargs):
        super(SearchResultForm, self).__init__(*args, **kwargs)
        for i, person in enumerate(persons):
            self.fields['person_%d' % i] = forms.BooleanField(required=False, custom_data=person)

[编辑]

我希望能够做到这样的事情:

  <form action="{% url 'test2' %}" method="GET">
    {% for field in result_form %}
        <div class="fieldWrapper">
            {{ field.first_name }} {{ field.second_name }}
        </div>
    {% endfor %}
    <input type="submit" value="test">
  </form>

我希望能够使用任何人拥有的属性: {{ field.first_name }} {{ field.second_name }} 甚至 {{ field.company.address }}

1 个答案:

答案 0 :(得分:0)

如果您只是希望将数据放在模板中的输入附近,您可以像这样向字段添加属性:

您可以将它们定义为表单类的一部分,如下所示:

class MyForm(forms.Form):
    example = forms.CharField(widget=forms.TextInput(
        attrs={"placeholder": "This will go in the placeholder attribute of the input element."}))

您也可以在 init 方法中执行此操作:

def __init__(self, *args, **kwargs):
    super(MyForm, self).__init__(*args, **kwargs)
    self.fields['example'].widget.attrs['placeholder'] = "This will go in the placeholder attribute of the input element."