promaxdev
promaxdev

Reputation: 495

Form fields in django templates

I have a form like the one below

class Form(forms.Form):
   chr1 = forms.CharField(widget=forms.TextInput())
   email = forms.EmailField()
   chr2 = forms.CharField()

And my view code is like this

def template(request):
    form = Form({})
    return render(request, 'mytemplate.html', {'form': form})

My template is like this

{% for field in form.fields %}
{{ field.label_tag }}: {{ field }}
{% endfor %}

I expect this to output a set of Input fields. But the above snippet is giving an output as given below

: chr1
: email
: chr2 

Upvotes: 2

Views: 4342

Answers (1)

CIGuy
CIGuy

Reputation: 5114

According to the documentation here you should be iterating on the form object itself not the fields. So instead of form.fields, just use form.

{% for field in form %}
    {{ field.label_tag }}: {{ field }}
{% endfor %}

I just found this duplicate question as well: django: form.fields not iterating through instance fields

Upvotes: 3

Related Questions