Rendering a form by looping through its fields in a template

 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. Making the HTTP object available globally across the app by sleepycal 3 years, 2 months ago
  2. Cache any function (with its arguments) by bkroeze 6 years, 12 months ago
  3. Days Since Filter by joe4444 7 years, 1 month ago
  4. mark a required field by "*" in a template by brunobord 6 years, 5 months ago
  5. {% ifthis FOO isoneof BAR BAZ ... %} by sjl 3 years, 11 months ago

Comments

(Forgotten your password?)