Login

Display values from a bound (submitted) form

Author:
masida
Posted:
March 13, 2014
Language:
Python
Version:
1.6
Score:
0 (after 0 ratings)

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:

  1. fields that are not filled out
  2. if you want to exclude some fields from the final list
  3. ChoiceField (select or radio button)
  4. 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

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 8 months ago

Comments

Please login first before commenting.