Django form field grouping

django, django-forms, django-templates

Solution

Any logical way to group fields would work... say you have a method on your form that returns form fields that you explicitly group?

To save typing, perhaps a certain field prefix naming scheme?

class MyForm(forms.Form):
    group1_field = forms.CharField()
    group1_field = forms.CharField()
    group2_field = forms.CharField()
    group2_field = forms.CharField()

   def group1(self):
        return [self[name] for name in filter(lambda x: x.startswith('group1_'), self.fields.values()]

Perhaps set an attribute on the field you can filter by?

class MyForm(forms.Form):
    field = forms.CharField()
    field.group = 1

    field2 = forms.CharField()
    field2.group = 2

    def group1(self):
        return filter(lambda x: x.group == 1, self.fields.values())

    def group2(self):
        return filter(lambda x: x.group == 2, self.fields.values())

You could also use the regroup tag if you set these attributes.

{% regroup form.fields by group as field_group %}
{% for group in field_group %}
<div class="group_{{ group.grouper }}">
  {% for field in group.list %}
    {{ field }}
  {% endfor %}
</div>
{% endfor %}

Problem

Say I have a form with 20 fields, and I want to put 10 of these fields (group1) in a particular div environment and the other 10 fields (group2) in a different div environment. Something like: ``` <div class="class1"> {% for field in form.group1 %} {{ field.label}}: {{ field }} {% endfor %} </div> <div class="class2"> {% for field in form.group2 %} {{ field.label}}: {{ field }} {% endfor %} </div> ``` Any ideas how I could accomplish this by iterating over the fields? More generally, I would like to be able to do this with many different div environments and sets of form fields.

Original source

Related problems