dev9
dev9

Reputation: 2382

How to access initial values of form fields in a loop in Django templates

I want to display initial values of form fields in a template.

class MyForm(forms.Form):
    myfield = forms.CharField(max_length=100, initial='test')

When I call a specific field everything is fine, but when I loop over form, nothing happens.

{% for field in form.fields %}
    {{ field.initial }}            # output: (nothing)
{% endfor %}

{{ form.fields.myfield.initial }}  # output: 'test'

Is it expected behaviour? How can I access initial values in a loop?

Upvotes: 1

Views: 1835

Answers (2)

Cherif KAOUA
Cherif KAOUA

Reputation: 844

This should work :

{% for field in form %}
    {{ field.field.initial }}
{% endfor %}

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599470

Loop over form itself.

{% for field in form %}

Upvotes: 2

Related Questions