I wanted to write a custom subclass of FormWrapper and FormFieldWrapper that automatically generates the label tags so instead of writing <label for="id_foo">{% trans "foo" %}{{ foo }} I could just write {{ foo }}. This proved to be impossible since crucial data about the field is not carried over to the manipulator and so cannot be extracted at a later time. I have attached a patch that will make this possible (it's just one line: "man.Klass = klass" in get_manipulator()). After this change I can trivially make the class I wanted to like so:
from django.core import formfields
class FormFieldWrapper(formfields.FormWrapper):
def __init__(self, formfield, data, error_list, manipulator):
self.formfield, self.data, self.error_list = formfield, data, error_list
self.field_name = self.formfield.field_name # for convenience in templates
self.manipulator = manipulator
def __str__(self):
from django.utils.text import capfirst
from django.core import meta
opts = self.manipulator.Klass._meta
field = opts.get_field(self.field_name)
label_prefix = '<label for="' + self.formfield.get_id()+'">'+capfirst(field.verbose_name)
label_suffix = '</label>'
rendered_field = self.formfield.render(self.data)
if isinstance(field, meta.BooleanField):
return rendered_field + label_prefix+label_suffix+'<br />'
else:
return label_prefix + ':' + label_suffix + rendered_field+'<br />'
class FormWrapper(formfields.FormWrapper):
def __getitem__(self, key):
for field in self.manipulator.fields:
if field.field_name == key:
if hasattr(field, 'requires_data_list') and hasattr(self.data, 'getlist'):
data = self.data.getlist(field.field_name)
else:
data = self.data.get(field.field_name, None)
if data is None:
data = ''
return FormFieldWrapper(field, data, self.error_dict.get(field.field_name, []), self.manipulator)
raise KeyError
patch