Login

Stacked/Grouped Forms 2 - easy rendering forms

Author:
diverman
Posted:
November 9, 2009
Language:
Python
Version:
1.1
Score:
1 (after 2 ratings)

This snippet was inspired by 1783. It allows simply create groups of fields for template rendering.

 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
from django.forms.forms import BoundField

class FieldStack(object):
    """ EXAMPLE:

    class MyForm(forms.Form):
        first_name = forms.CharField()
        last_name = forms.CharField()
        website = forms.CharField()
        twitter = forms.CharField()
        facebook = forms.CharField()

        personal_info = FieldStack('first_name', 'last_name')
        contact_info = FieldStack('website', 'twitter', 'facebook')
    
    <ul>{% for field in form.personal_info %}
        <li>{{field.name}}: {{ field }}{{field.errors}}</li>
    {% endfor %}</ul>
    
    <table>{% for field in form.contact_info %}
        <tr><td>{{field.name}}</td><td>{{ field }}</td><td>{{field.errors}}</td></tr>
    {% endfor %}</table>
    """

    def __init__(self, *args):
        self.fields = args
        
    def __get__(self, form, objtype=None):
        for field in self.fields:
            yield BoundField(form, form.fields[field], field)

More like this

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

Comments

Please login first before commenting.