[Fixed]-Django Formset.is_valid() failing for extra forms

25đź‘Ť

âś…

Thanks Carl,
you led me to discover the root of my problem.

When creating a form with a choice field, which is required, we must set an initial value, otherwise the form will consider that field changed.

So for a form like this:

class SomeForm(forms.Form):

    A = 0
    B = 1
    C = 2
    D = 3

   choices = ((A, 'Aah'), (B, 'Baa'), (C, 'Caa'), (D, 'Daa'))

    # This is a required choice field
    pickme = forms.ChoiceField(choices=choices)

we do this:

pickme = forms.ChoiceField(choices=choices, initial=A)

Then when a formset checks the extra form it will see that pickme had an initial value of A, and it is A now as well, and will consider it unchanged.

10đź‘Ť

This is not the usual behavior of formsets. Formsets pass empty_permitted=True to all “extra” forms, and a form with empty_permitted that hasn’t been modified should always pass validation. Note that this works just fine in the Django admin (if you use inlines).

You must be doing something else in your code that is breaking this behavior somewhere. Post the full code of the relevant form?

👤Carl Meyer

Leave a comment