from django import forms from django.forms.forms import BoundField class StructuredForm: group_struct = [] def groups(self): group_list = [] for name, fields in self.group_struct: group_list.append((name, [BoundField(self, self.fields[fname], fname) for fname in fields])) return group_list ################# # # example form # class MyForm(forms.ModelForm, StructuredForm): group_struct = ((None, ["fieldname1"]), ("sectionname1", ["fieldname2", "fieldname3", "fieldname4"]), ("sectionname2", ["fieldname5", # ... ]), # ... ) class Meta: model = MyModel # exclude = ... # ... ##################### # # example template # """
{% for name, fields in form.groups %} {% if name %}
{{name}} {% endif %} {% for field in fields %} {% endfor %}
{{field.label}}{{field.errors}}{{field}}{% if field.help_text %}
{{field.help_text}}{% endif %}
{% if name %}
{% endif %} {% endfor %}

"""