Django Model formsets not validating

Posted on May 24, 2011 Comments

I had a problem recently with a site I was working on,  I was trying to allow a user to input details about a variable number of items through forms on the front end.  To acomplish this I was using Django's model formsets but I had a problem, the user was required to fill in each field, and the models were set up as required, however if a user left a form empty it would validate just fine.  I could not understand why the formset was validating when I had it set up as all required fields.

A little google-fu led me to this answer on StackOverflow which informed me that formsets always pass empty_permitted=True to all forms added to the formset via the "extra" argument, which was exactly how I was adding the variable number of forms I needed per user.  The forms with extra_permitted=True will always pass validation as long as they havent been modified.

This had told me what the problem was but not how to solve it, so I am going to document my solution here so that anyone else who encounters this problem will know what to do.

I first subclassed BaseModelFormSet from django.forms.models:

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

I looped through each form and set empty_permitted to False.

I then had to go into my view and add formset=MyModelForm to my modelformset_factory:

MyFormSet = modelformset_factory(MyModel, formset=MyModelFormSet, extra=whatever, max_num=whatever)
        my_formset = MyFormSet(data=request.POST or None, queryset=MyModel.objects.none())

Now we have a wonderful formset with easy built in Django validation working - magic!

blog comments powered by Disqus