Customizable newforms labels with a template tag

 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
28
29
30
31
32
33
from django.template import Library
from django.newforms.util import flatatt

register = Library()

@register.inclusion_tag("forms/label.html")
def label(field, contents=None, attrs=None):
    if isinstance(attrs, basestring):
        attrs = [tuple(pair.split('=')) for pair in attrs.split(',')]
    attrs = dict(attrs or {})
    widget = field.field.widget
    for_id = widget.id_for_label(widget.attrs.get('id') or field.auto_id)
    contents = contents or field.label
    return {'field': field, 'id': for_id, 'contents': contents, 'attrs': attrs}

@register.filter
def attrlist(attrs):
    attrs = dict(attrs)
    return flatatt(attrs)
attrlist.is_safe = True

# My "forms/label.html" looks like this...
"""
{% load forms %}

{% if not field.is_hidden %}
{% with field.field.required as required %}
<label for="{{ id }}"{{ attrs|attrlist }}{% if required and not attrs.class %} class="required"{% endif %}>
    {{ contents }}
</label>
{% endwith %}
{% endif %}
"""

More like this

  1. Template Filter attr by marinho 5 years, 12 months ago
  2. Form rendering using a template instead of builtin HTML by leoh 6 years, 10 months ago
  3. FieldsetForm by Ciantic 7 years ago
  4. RangeField and RangeWidget by marinho 5 years, 6 months ago
  5. Type checking templatetag filters by marcorogers 4 years, 1 month ago

Comments

(Forgotten your password?)