Django-多个内联表单使用另一个表单集数据验证1个表单集

时间:2019-11-06 19:44:46

标签: django validation django-forms django-views inline-formset

我有一个主要模型:

在视图中使用的

MainModel-> MainModelForm

我也有2种以MainModel作为主键的内联表单 InlineModel1 => InlineModel1Form (formset = CustomInlineModel1Formset(BaseInlineFormset)),它具有自己的一组验证。它是1或无设置,即它不是必需的,但是一旦添加,它就会进行一些验证。从BaseInlineFormSet使用CustomSetup效果很好。

但是,我有另一种型号-  不需要InlineModel2-直到用户在InLineModel1Form中输入至少1行。我在如何发送/验证此问题上不知所措,即使用InlineModel1form数据并检查InlineModel2Form中是否添加了任何行 形成。

我需要分别设置两组内联表单,所以将一处显示所有内容的mixin对我不起作用。

forms.py:

class CustomInlineModel2Formset(BaseInlineFormSet):
    def clean(self):
        cleaned_data = super(CustomInlineModel2Formset, self).clean()

        if any(self.errors):
            return

        i=0
        # https://gist.github.com/nspo/cd26ae2716332234757d2c3b1f815fc2
        for form in self.forms:
            if(not form.is_valid()):
                continue
            if(form.cleaned_data and not form.cleaned_data.get('DELETE')):
                i = i+1
                print(form.cleaned_data)
                # Use data from request.POST/but from InlineModel1 and add error to field2 in InlineModel2
                # Ensure atleast 1 entry is here - so how to run validations, outside this loop?
    InlineModel2FormSet = forms.inlineformset_factory(MainModel, InlineModel2,
        widgets = {},
        form=InlineModel2Form,
        formset = CustomInlineModel2Formset,
        exclude=[],
        min_num = 0, # min_num is to be validated as 1 only if InlineModel1Form has any entries added 
        max_num = 2,
        extra=0,
        can_delete=True,
        # formfield_callback=None
    )

0 个答案:

没有答案