Login

Get default form data

Author:
dgouldin
Posted:
February 28, 2011
Language:
Python
Version:
Not specified
Tags:
forms widgets
Score:
2 (after 2 ratings)

Given an unbound form, determine what data would be generated from POSTing the form unchanged. The goal is to end up with a dict such that, passed into another form constructor as its data kwarg, form.changed_data == [].

 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
def get_default_form_data(form):
    """
    Given an unbound form, determine what data would
    be generated from POSTing the form unchanged.
    """
    def value_from_widget(initial_value, widget):
        value = initial_value
        if value != '':
            if hasattr(widget, '_format_value'):
                value = widget._format_value(value)
            value = force_unicode(value)
        return value

    data = {}
    for name, field in form.fields.items():
        if isinstance(field.widget, forms.MultiWidget):
            value = field.widget.decompress(form.initial[name])
            for i, widget in enumerate(field.widget.widgets):
                try:
                    widget_value = value[i]
                except IndexError:
                    widget_value = None
                data['%s_%s' % (name, i)] = value_from_widget(widget_value, widget)
        else:
            data[name] = value_from_widget(form.initial[name], field.widget)

    if form.prefix:
        return dict([('%s-%s' % (form.prefix, k), v) for k,v in data.items()])
    else:
        return data

More like this

  1. Many2Many comma separated form field by haloween 5 years, 5 months ago
  2. Multiple models display form by lbolognini 7 years, 11 months ago
  3. Dropbox Chooser Form Widget by tcfitzgerald 1 year, 10 months ago
  4. Add model form field meta data in a DRY way by jedie 6 years, 3 months ago
  5. Easier prefix handling for forms by gsakkis 5 years, 2 months ago

Comments

Please login first before commenting.