Login

FieldStack - easy form template rendering

Author:
diverman
Posted:
May 26, 2010
Language:
Python
Version:
1.2
Score:
2 (after 2 ratings)

FieldStack simplifies forms template rendering. This is enhanced version of snippet 1786

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

class FieldStackLazy(object):
    def __init__(self, form, *fields, **attrs):
        self.form, self.fields = form, fields
        self.__dict__.update(attrs)

    def __iter__(self):
        for field in self.fields:
            yield BoundField(self.form, self.form.fields[field], field)

class FieldStack(object):
    def __init__(self, *fields, **attrs):
        self.fields, self.attrs = fields, attrs

    def __get__(self, form, objtype=None):
        return FieldStackLazy(form, *self.fields, **self.attrs)

#################################################################
# Example form
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', title='Personal info', color='red')
    contact_info = FieldStack('website', 'twitter', 'facebook', title='Contact info', color='green')

# Example template
<div style="color:{{form.personal_info.color}}">{{form.personal_info.title}}</div>
    
<ul>{% for field in form.personal_info %}
    <li>{{field.name}}: {{ field }}{{field.errors}}</li>
{% endfor %}</ul>
    
<div style="color:{{form.contact_info.color}}">{{form.contact_info.title}}</div>

<table>{% for field in form.contact_info %}
    <tr><td>{{field.name}}</td><td>{{ field }}</td><td>{{field.errors}}</td></tr>
{% endfor %}</table>

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.