Login

Rendering a form by looping through its fields in a template

Author:
simon
Posted:
September 14, 2008
Language:
Python
Version:
1.0
Tags:
newforms templates foms
Score:
3 (after 5 ratings)

See also this thread. I'm an idiot; this snippet has now been updated to show how you do this without re-inventing the wheel.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class PersonForm(Form):
    name = forms.CharField()
    email = forms.EmailField()
    age = forms.IntegerField()

# And here's how you would output its fields using a custom template:

{% for field in form %}
<div>
  {{ field.errors }}
  {{ field.label_tag }}: {{ field }}
</div>
{% endfor %}

# By default, {{ field.errors }} outputs a <ul class="errorlist"> containing
# the validation errors, or a blank string if there are none. If you want to 
# further customise the way in which errors are displayed, you can do this:

{% for field in form %}
<div>
  {% if field.errors %}
    {% for error in field.errors %}
      <p style="color: red">Oh no! {{ error }}</p>
    {% endfor %}
  {% endif %}
  {{ field.label_tag }}: {{ field.as_html }}
</div>
{% endfor %}

More like this

  1. Cache any function (with its arguments) by bkroeze 8 years, 1 month ago
  2. Dynamic SITE_ID thread-safe by jhg 1 year, 1 month ago
  3. Days Since Filter by joe4444 8 years, 2 months ago
  4. mark a required field by "*" in a template by brunobord 7 years, 6 months ago
  5. {% ifthis FOO isoneof BAR BAZ ... %} by sjl 5 years ago

Comments

Please login first before commenting.