Login

Form row filter

Author:
kylefox
Posted:
February 14, 2008
Language:
Python
Version:
.96
Tags:
newforms forms templates filters
Score:
12 (after 12 ratings)

I love newforms. But sometimes using {{ form }} within a template doesn't give you enough flexibility. The other option, manually defining the markup for each field, is tedious, boring and error-prone.

This is an example of how you can use a template filter to get the best of both worlds. Use it like this to render an entire form:

{% for field in form %}

    {{ field|form_row }}

{% endfor %}

Or use it on a per-field basis:

<fieldset>

    {{ form.first_name|form_row }}

    {{ form.last_name|form_row }}

</fieldset>

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from django import template

register = template.Library()

@register.filter
def form_row(value):
        # Change the template string below to suit your needs.
	row = template.Template("""
	<div class="form-row{% if field.errors %} errors{% endif %}">
		{{ field.errors }}{{ field.label_tag }}{{ field }}
	</div>
	""")
	return row.render(template.Context({'field': value}))

More like this

  1. Fieldsets for Views by Nad 5 years, 7 months ago
  2. SectionedForm by marinho 7 years, 2 months ago
  3. Form splitting/Fieldset templatetag by peritus 6 years, 12 months ago
  4. BetterForm with fieldsets and row_attrs by carljm 6 years, 6 months ago
  5. FieldsetForm by Ciantic 8 years, 4 months ago

Comments

pihentagy (on June 23, 2008):

Why not create a method like form.as_table()?

#

Please login first before commenting.