tag: render form field

 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. BetterForm with fieldsets and row_attrs by carljm 4 years, 3 months ago
  2. StaticField for non-changing text data in forms by V 3 years, 12 months ago
  3. AjaxForm Base Classes by btaylordesign 2 years, 2 months ago
  4. UKPhoneNumberField GB v2 by g1smd 8 months, 2 weeks ago
  5. Changing the look of newforms as_table with a custom BaseForm by bikeshedder 5 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'}}

#

(Forgotten your password?)