Template filter to markup form fields with optional 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

  1. really spaceless (trim spaces at line start) by wolfram 6 years, 3 months ago
  2. Nice form errors by SmileyChris 4 years, 6 months ago
  3. Generic CSV Export by zbyte64 5 years, 10 months ago
  4. Complex Form Preview by smagala 5 years ago
  5. SectionedForm by marinho 5 years, 10 months ago

Comments

(Forgotten your password?)