Reputation: 189
I have a parent and several child forms using an inline formset. It works fine.
Depending on a value in the parent form, I need to check that the right number of child forms has been submitted.
I know I can access the parent form using self.instance.FOO when overriding BaseInlineFormSet and again this works fine, but I can't find a way to determine how many actual forms have been submitted and vitally have data in them.
Anyone know how?
Many thanks
Upvotes: 0
Views: 612
Reputation: 189
Thank you Daniel for pointing me in the right direction. I achieved what I needed by overriding baseinlineformset and doing the following in the clean method:
# submitted form counter
i = 0
for form in self.forms:
cleaned_data = form.cleaned_data
if cleaned_data:
# discounts forms marked for deletion
if not self._should_delete_form(form):
i = i + 1
if self.instance.ownership.type == 'Joint' and i < 2:
raise ValidationError(
"You must enter both clients when specifying joint "
"ownership."
)
etc.
I also found that I also needed to remove any forms being deleted during the same post from the form count.
Upvotes: 0
Reputation: 599946
In the formset clean
method, self.cleaned_data
will be a list of dictionaries - one for each form. So you can do:
class MyInlineFormSet(formsets.InlineFormSet):
def clean(self):
if len(self.cleaned_data) != self.instance.my_value:
raise forms.ValidationError('wrong number of forms')
Upvotes: 3