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