FieldStack - easy form 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
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. Stacked/Grouped Forms 2 - easy rendering forms by diverman 4 years, 5 months ago
  2. BetterForm with fieldsets and row_attrs by carljm 5 years, 2 months ago
  3. Fieldsets for Views by Nad/ 4 years, 2 months ago
  4. Forms splitted in fieldsets by gustavo80br 6 years ago
  5. FieldsetForm by Ciantic 7 years ago

Comments

(Forgotten your password?)