Login

Display values from a bound (submitted) form

Author:
masida
Posted:
March 13, 2014
Language:
Python
Version:
1.6
Tags:
template email form
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. FieldAccessForm (per-field user access for forms derived from models) by Killarny 6 years, 9 months ago
  2. Readonly fields on Form/Modelform by Killarny 6 years, 5 months ago
  3. Command to dump data as a python script by willhardy 7 years, 1 month ago
  4. Multiple-Submit-Button Widget for Choice Field by Archatas 6 years, 12 months ago
  5. db_dump.py - for dumpping and loading data from database by limodou 8 years, 5 months ago

Comments

Please login first before commenting.