Form field sets

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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:

        <form method="POST" action="">
          <fieldset>
            <legend>Name</legend>
            {% for field in form.fieldsets.name_fields %}
              {% include "includes/form_field.html" %}
            {% endfor %}
          </fieldset>

          <fieldset>
            <legend>Contact</legend>
            {% for field in form.fieldsets.contact_fields %}
              {% include "includes/form_field.html" %}
            {% endfor %}
          </fieldset>
        </form>
    """
    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

More like this

  1. Submit button as a form field by roxeteer 3 years, 3 months ago
  2. VAT field by rodnsi 4 years, 11 months ago
  3. clean validation for dynamic form fields by leveillej 3 years, 11 months ago
  4. Adding Fields to Registration Form [or Multiple Inheritance of forms] by simonkagwe 2 years, 6 months ago
  5. ABN and ACN Form Fields by julan 4 years, 12 months ago

Comments

SixDegrees (on July 29, 2011):

It doesn't work.

#

(Forgotten your password?)