Login

Get default form data

Author:
dgouldin
Posted:
February 28, 2011
Language:
Python
Version:
Not specified
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. Template tag - list punctuation for a list of items by shapiromatron 2 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 9 months, 4 weeks ago
  5. Help text hyperlinks by sa2812 10 months, 3 weeks ago

Comments

Please login first before commenting.