Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django and empty formset are valid

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.

like image 969
dancing Avatar asked Dec 19 '10 02:12

dancing


People also ask

What is formset Django?

A formset is a layer of abstraction to work with multiple forms on the same page. It can be best compared to a data grid. Let's say you have the following form: >>> from django import forms >>> class ArticleForm(forms.

What is inline formset in Django?

Django formset allows you to edit a collection of the same forms on the same page. It basically allows you to bulk edit a collection of objects at the same time.


2 Answers

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.

like image 111
Jonas Avatar answered Sep 22 '22 20:09

Jonas


@Jonas, thanks. I used your description to solve my problem. I needed the a form to NOT validate when empty. (Forms added with javascript)

class FacilityForm(forms.ModelForm):
    class Meta:
        model = Facility

    def __init__(self, *arg, **kwarg):
        super(FacilityForm, self).__init__(*arg, **kwarg)
        self.empty_permitted = False


 facility_formset = modelformset_factory(Facility, form=FacilityForm)(request.POST)

It will make sure any displayed forms must not be empty when submitted.

like image 40
Daniel Backman Avatar answered Sep 24 '22 20:09

Daniel Backman