- Author:
- crucialfelix2
- Posted:
- November 25, 2009
- Language:
- Python
- Version:
- 1.1
- Score:
- 3 (after 3 ratings)
this solves a common problem where you want to specify html tag attributes for form fields in the template itself and not have to do it by writing a custom form class.
eg. the size of the field, css classes, tabindex etc.
usage: {% render_field form.comments "cols=40,rows=5,class=text,tabindex=2" %}
where form.comments is a form field with a text area widget
it will show data (if the form is bound or if there is initial data) and will display errors if the field has errors
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 | @register.inclusion_tag("form_tools/render_field.html")
def render_field(field,attributes=''):
""" render a field with its errors, optionally passing in
attributes eg.:
{% render_field form.name "cols=40,rows=5,class=text,tabindex=2" %}
this is equivalent to
<p>{{form.name.errors}}</p>
{{ form.name }}
but will also add the custom attributes
"""
return {'errors':field.errors,'widget':make_widget(field,attributes)}
def make_widget(field,attributes):
attr = {}
if attributes:
attrs = attributes.split(",")
if attrs:
for at in attrs:
key,value = at.split("=")
attr[key] = value
return field.as_widget(attrs=attr)
## render_field.html
{% if errors %}<p>{{ errors }}</p>{% endif %}
{{ widget }}
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
This is a a bit simpler:
Usage:
#
Please login first before commenting.