Login

Rendering a form by looping through its fields in a template

Author:
simon
Posted:
September 14, 2008
Language:
Python
Version:
1.0
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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.