def get_fieldsets_attr(sets, cache_attr='_fieldsets'): """ Get a form attribute for getting groups of (bound) fields. class MyForm(forms.Form): first_name = forms.Charfield() last_name = forms.Charfield() email = forms.Charfield() phone = forms.Charfield() SETS = {'name_fields': ('first_name', 'last_name'), 'contact_fields': ('email', 'phone')} fieldsets = get_fieldsets_attr(sets=SETS) This is specially usefull in templates:
""" def inner(self): if not hasattr(self, cache_attr): from django.forms.forms import BoundField fieldsets = {} for key, fieldnames in sets.items(): fieldsets[key] = [] for fieldname in fieldnames: fieldsets[key].append(BoundField(self, self.fields[fieldname], fieldname)) self.cache_attr = fieldsets return self.cache_attr return inner