Login

Form field sets

Author:
gonz
Posted:
January 21, 2010
Language:
Python
Version:
1.1
Score:
2 (after 2 ratings)

Create form atribute(s) for grouping (bound) fields.

 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. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 3 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

SixDegrees (on July 29, 2011):

It doesn't work.

#

Please login first before commenting.