Login

tag: render form field

Author:
crucialfelix2
Posted:
November 25, 2009
Language:
Python
Version:
1.1
Tags:
forms
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. Readonly fields on Form/Modelform by Killarny 6 years, 2 months ago
  2. AjaxForm Base Classes by btaylordesign 4 years, 2 months ago
  3. Class-based process form view. by I159 3 years, 5 months ago
  4. ajax_validator generic view by amitu 6 years, 7 months ago
  5. Form rendering using a template instead of builtin HTML by leoh 7 years, 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.