Django formset cleaned_data empty when form submit unchanged

I'm having a weird issue with Django 1.4 and formsets: when the submitted data is unchanged, the cleaned_data field in the formset is empty even though the formset itself passes validation.

Here's an example:

class NameForm(forms.Form):
    name = forms.CharField(required=False, initial='Foo')

def welcome(request):

    Formset = formset_factory(NameForm, extra=1)
    if request.method == 'POST':
        formset = Formset(request.POST)
        print '1.Formset is valid?', formset.is_valid()
        print '2.Formset', formset
        print '3.Formset cleaned_data', formset.cleaned_data
        formset = Formset()
    return render_to_response('template.html', locals())


Although formset

valid and actually contains data, line 3 lists the empty dictionary, unless I actually changed the initial value in the field.

This seems strange to me, but I am probably doing something wrong. Any help?


source to share

2 answers

The formset displays a bunch of forms as well as several hidden input fields containing information such as the maximum number of forms. Thus, a correctly POSTed formet always contains data.

And, the original 'Foo' inside the CharField name

is the reason formet got an empty dictionary. If a empty_permitted

form is set to True and all form elements are equal to its initial value, Django will treat the form as empty and set its cleaned_data to be an empty dict. empty_permitted

by default False, formet will set to True for additional forms. Thus, after you clicked the submit button without editing the "Foo" value, the form instance was treated as empty, so the formal packaging filling the form received empty cleaned_data.



It happened to me. @okm is correct, but it's not clear from his answer how to fix it. See this answer for a solution:

class MyModelFormSet(BaseModelFormSet):
    def __init__(self, *args, **kwargs):
        super(MyModelFormSet, self).__init__(*args, **kwargs)
        for form in self.forms:
            form.empty_permitted = False




All Articles