With this, you can group form fields very easily. Since it does not create any html, you can use it not only to create fieldsets (with tables, lists, etc).
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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | from django import forms
from django.forms.forms import BoundField
class StructuredForm:
group_struct = []
def groups(self):
group_list = []
for name, fields in self.group_struct:
group_list.append((name, [BoundField(self,
self.fields[fname],
fname) for fname in fields]))
return group_list
#################
#
# example form
#
class MyForm(forms.ModelForm, StructuredForm):
group_struct = ((None,
["fieldname1"]),
("sectionname1",
["fieldname2", "fieldname3",
"fieldname4"]),
("sectionname2",
["fieldname5",
# ...
]),
# ...
)
class Meta:
model = MyModel
# exclude = ...
# ...
#####################
#
# example template
#
"""
<form action="#" method="post">
{% for name, fields in form.groups %}
{% if name %}
<fieldset>
<legend>{{name}}</legend>
{% endif %}
<table>
{% for field in fields %}
<tr><th>{{field.label}}</th><td>{{field.errors}}{{field}}{% if field.help_text %}<br/>{{field.help_text}}{% endif %}</td></tr>
{% endfor %}
</table>
{% if name %}
</fieldset>
{% endif %}
{% endfor %}
<p>
<input type="submit" name="submit" value="Send" />
</p>
</form>
"""
|
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.