# 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}))