Django:传递表单值元素id或类名

时间:2015-08-06 11:19:45

标签: python django templates elements formset

我有以下表格:

class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel
        fields = ["name", "surname", "idnumber"]

MyFormSet = modelformset_factory(MyModel,
                                 form=MyForm,
                                 extra=0)

在views.py中:

def completeForm(request):
    formset = MyFormSet(queryset=MyModel.objects.all())
    context = {'formset': formset}
    return render(request, 'mytemplate.html', context)

因此,在我的模板中,我想执行以下操作:

{{ formset.management_form }}
{% for form in formset %}
  <p id="{{ form.name }}">{{ form.name }}</p>
  <p id="{{ form.surname }}">{{ form.surname }}</p>
  <p id="{{ form.idnumber }}">{{ form.idnumber }}</p>
{% endfor %}}

这不起作用..有没有办法做到这一点,还是应该在窗体小部件中添加id?如果是这样,我怎么能在forms.py?

中这样做

2 个答案:

答案 0 :(得分:0)

表单需要简单:

{{ formset.management_form }}
{% for form in formset %}
  {{ form.name }}
  {{ form.surname }}
  {{ form.idnumber }}
{% endfor %}}

这应该有效。希望这会有所帮助:)

答案 1 :(得分:0)

我应该寻找attrs个小部件。在一个简单的形式,你可以这样做:

class FormLogin(forms.Form):
    email = forms.CharField(max_length=40, widget=forms.TextInput(attrs={'class': 'form-control'}))

modelform中:

    class MyForm(forms.Form):
    class Meta:
        model = MyModel
        fields = ["name", "surname", "idnumber"]
        widgets = {
            'name': forms.TextInput(attrs={'id':'name', 'class':'form-control'}),
            'surname': forms.TextInput(attrs={'class':'form-control'}),
            'idnumber': forms.TextInput(attrs={'class':'form-control'}),
        }