django inline_formset - form.empty_permitted = False doesn't work

你说的曾经没有我的故事 提交于 2020-01-25 09:04:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!