Login

tag: render form field

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

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

diverman (on December 4, 2009):

This is a a bit simpler:

@register.filter
@register.simple_tag
def render_field(bound_field, attributes):
    import re

    return bound_field.as_widget(attrs=(
        dict([ attr.split('=') for attr in attributes.split(',') ])
        if re.compile( r'^(\w+=\w+,)*\w+=\w+,?$' ).match(attributes)
        else {}
    ))

Usage:

{% render_field form.name 'cols=10,rows=3,class=text,tabindex=2' %}

{{ form.name|render_field:'cols=10,rows=3,class=text,tabindex=2'}}

#

Please login first before commenting.