Template filter to mark-up individual form fields.
Usage :
In template - {% load form_custom %}
then for a form field - {{ form.field|form_row:"default" }} for default wrapper
or - {{ form.field|form_row:"lbl_cls=some_class_name&reqd=no" }} to pass option args seperated by &
Optional args are :- wrapper_cls - override default field wrapper div class name error_cls - override default field error div class name lbl_cls - override default label_tag div class name label - yes/no default is yes - output label_tag reqd - yes/no default is yes - marks up required fields as bold with label ending with *
See code for all default args.
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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | # place code into templatetags/form_custom.py
from django.http import QueryDict
register = template.Library()
@register.filter
def form_row(obj,args):
# default args
arg_wrapper_cls = "field_wrapper"
arg_error_cls = "field_error_right"
arg_lbl_cls = "field_label_160"
arg_label = "yes"
arg_reqd = "yes"
arg_reqd_smb = "*"
# get any passed args and replace into default args
arg_keys = QueryDict(args)
if arg_keys.has_key('wrapper_cls'):
arg_wrapper_cls = arg_keys['wrapper_cls']
if arg_keys.has_key('error_cls'):
arg_error_cls = arg_keys['error_cls']
if arg_keys.has_key('lbl_cls'):
arg_lbl_cls = arg_keys['lbl_cls']
if arg_keys.has_key('label'):
arg_label = arg_keys['label']
if arg_keys.has_key('reqd'):
arg_reqd = arg_keys['reqd']
# get field required
required = obj.form.fields[obj.name].required
# set arg_reqd
if not required and arg_reqd == "yes":
arg_reqd = 'no'
# field wrapper
html = '<div class="' + arg_wrapper_cls + '">'
# field label
if arg_label == "yes":
if arg_reqd == "no":
html += "<div class=" + '"' + arg_lbl_cls + '"' + ">{{ field.label_tag }}</div>"
else:
html += "<div class=" + '"' + arg_lbl_cls + '"' + "><b>{{ field.label_tag }}" + arg_reqd_smb + "</b></div>"
# field control
html += """<div class="field_control">{{ field }}</div>"""
# field error
html += "<div class=" + '"' + arg_error_cls + '"' + ">{{ field.errors }}</div> </div>"
row = template.Template(html)
return row.render(template.Context({'field': obj}))
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 8 months ago
Comments
Please login first before commenting.