问题
I have two models - Invoice and InvoiceItem.
I have the following formset.
class InvoiceItemFormSet(forms.BaseInlineFormSet):
def __init__(self, *args, **kwargs):
super(InvoiceItemFormSet, self).__init__(*args, **kwargs)
for form in self.forms:
form.empty_permitted = False
def clean(self):
cleaned_data=super(InvoiceItemFormSet, self).clean()
print('inside form.clean')
Inside my CreateViw, I have the following code for the formset.
ItemInlineFormSet = inlineformset_factory(Invoice,
InvoiceItem, form=InvoiceItemForm, extra=1,
can_delete=False,validate_min=True, min_num=1,
formset=InvoiceItemFormSet)
However, when I press the Submit button, even if all (two) forms of the formset are empty, the parent form gets submitted.
What I'm missing here?
Thanks.
回答1:
Instead of using
for form in self.forms:
form.empty_permitted = False
I added
def clean(self):
if self.has_changed() == False:
raise forms.ValidationError('Please add at least one item to the invoice.')
to the formset and the following to the form_valid() of the CreateView
if item_formset.is_valid() == False:
return self.render_to_response(self.get_context_data(form=form,item_formset=item_formset ))
来源:https://stackoverflow.com/questions/49778252/django-inline-formset-form-empty-permitted-false-doesnt-work