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

与自定义数据关联的Django动态表单字段,django,django-forms,Django,Django Forms,我想访问传递对象的属性。可能吗 我试过类似的方法,但不起作用:( [编辑] 我希望能够做到以下几点: <form action="{% url 'test2' %}" method="GET"> {% for field in result_form %} <div class="fieldWrapper"> {{ field.first_name }} {{ field.second_name }} &

我想访问传递对象的属性。可能吗

我试过类似的方法,但不起作用:(

[编辑]

我希望能够做到以下几点:

  <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>
class MyForm(forms.Form):
    example = forms.CharField(widget=forms.TextInput(
        attrs={"placeholder": "This will go in the placeholder attribute of the input element."}))

{结果形式为%的字段的百分比}
{{field.first_name}{{field.second_name}}
{%endfor%}
我希望能够使用人员具有的任何属性:
{{field.first_name}}
{{field.second_name}}
甚至
{{field.company.address}

如果您只是希望在模板中的输入附近有数据,您可以向该字段添加属性,如下所示:

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."
可以将它们定义为表单类的一部分,如下所示:

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

我想你需要像
persons=request.POST.getlist('persons[])
(并相应地命名文本字段)这样的东西,所以我将不得不在模板中手动绑定数据?@Peter你的答案是a)错误的,b)与问题无关。首先,Django不使用Rails/PHP
字段[]
约定。@STX_user3581226我不确定实际的问题是什么。这到底出了什么问题,自定义数据应该是什么?@Daniel是的,是的,请看。我把它作为一条评论发布,因为这个问题对我来说不是很清楚,我只是想把TS指向一个可能正确的方向。我知道这个方法,但是如果我想保持关系,传递变量如
field.company.address
field.company.name
,它就不太好了。在这种情况下,每个变量都必须通过显式和手动方式传递。那么为什么不在视图中作为上下文变量传递呢?