Login

Form row filter

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

Comments

pihentagy (on June 23, 2008):

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

#

Please login first before commenting.