Reputation: 477
In a modelformset with 3 copies of the form, how do i specify that only the first set is required but the rest can be blank or null?
Upvotes: 1
Views: 946
Reputation: 18008
You can subclass BaseModelFormSet
so it modifies the first form and makes it required:
from django.forms.models import BaseModelFormSet
class OneRequiredFormSet(BaseModelFormSet):
def _construct_form(self, i, **kwargs):
f = super(OneRequiredFormSet, self)._construct_form(i, **kwargs)
if i == 0:
f.empty_permitted = False
f.required = True
return f
Then you can use the formset
keyword argument to tell modelformset_factory
to use your new class:
from django.forms.models import modelformset_factory
ParticipantFormSet = modelformset_factory(Participant, extra=1,
form=ParticipantForm,
formset=OneRequiredFormSet)
Upvotes: 0
Reputation: 42040
I've used something like this for inline formsets:
class BaseSomethingFormset(BaseInlineFormSet):
def __init__(self, *args, **kwargs):
super(BaseSomethingFormset, self).__init__(*args, **kwargs)
self.forms[0].empty_permitted = False
self.forms[0].required = True
The form fields must be by default set to required=False
Upvotes: 2
Reputation: 34573
Matthew Flanagan has a package of things for Django, and in that package is the RequireOneFormset class. You can easily extend this class to require 3 forms instead of one.
Hope that helps you out.
Upvotes: 1