Get default form 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. Custom admin widgets by field type by dgouldin 4 years, 2 months ago
  2. Complex Formsets, Redux by smagala 3 years, 2 months ago
  3. Improved Pickled Object Field by taavi223 3 years, 9 months ago
  4. Return to a filtered changelist on change form save by richardbolt 2 years, 9 months ago
  5. Complex Form Preview by smagala 4 years, 1 month ago

Comments

(Forgotten your password?)