Function that takes a bound form (submitted form) and returns a list of pairs of field label and user chosen value.
It takes care of:
- fields that are not filled out
- if you want to exclude some fields from the final list
- ChoiceField (select or radio button)
- MultipleChoiceField (multi-select or checkboxes)
Usage:
if form.is_valid():
form_data = get_form_display_data(form, exclude=['captcha'])
It's trivial to display the list of pairs in a template:
{% for key, value in form_data %}
{{ key }}: {{ value }}{% endfor %}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | import types
def get_form_display_data(form, exclude=None):
""" A generator for getting user displayable data from a (bound)
form instance. Optionally, you can exclude specific fields from
the result. """
cleaned_data = form.cleaned_data
for field in form:
if exclude and field.name in exclude:
continue
value = field.value() or ''
if hasattr(field.field, 'choices'):
if isinstance(value, types.StringTypes):
# One choice only
value = next(v for k, v in field.field.choices if k == value)
else:
# Multiple choices
value = u', '.join(v for k, v in field.field.choices if k in value)
yield (field.label, value)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 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.