Django and empty formset are valid

dancing picture dancing · Dec 19, 2010 · Viewed 13.7k times · Source

I have a little problem with the formset.

I must display several formsets in a page, and each formset has several forms. So i did something like that :

#GET
for prod in products:
     ProductFormSet = modelformset_factory(Product,exclude=('date',),extra=prod.amount)
     formsset.append(ProductFormSet(prefix="prod_%d"%prod.pk))

#POST
for prod in products:
     ProductFormSet = modelformset_factory(Product,exclude=('date',),extra=prod.amount)
     formsset.append(ProductFormSet(request.POST,prefix="prod_%d"%prod.pk))

The problem is when I submit the page, the empties forms are 'automatically' valid (without check), but if I fill one field in one form, the check works on it.

I don't know why, so if anyone has an idea,

thanks.

Answer

Jonas picture Jonas · Mar 22, 2011

I ran into this question while researching another problem. While digging through the Django source in search of a solution for my problem, I found the answer to this question so I'll document it here:

When a form is allowed to have empty values (this applies for empty forms contained within a formset) and the submitted values haven't been changed from the initial ones, the validation is skipped. Check the full_clean() method in django/forms/forms.py (line 265 in Django 1.2):

# If the form is permitted to be empty, and none of the form data has
# changed from the initial data, short circuit any validation.
if self.empty_permitted and not self.has_changed():
     return

I'm not sure what kind of solution you're looking for (also, this question is already somewhat dated) but maybe this will help someone in the future.