简体   繁体   English

Django内联表单集验证

[英]Django inline formset validation

I have the following models: 我有以下型号:

class CaseForm(ModelForm):
    class Meta:
        model = Case
        fields = '__all__'


class ClientForm(ModelForm):

    class Meta:
         model = Client
         fields = '_all__'

CaseClientFormset = inlineformset_factory(Case, Client, form=ClientForm,
                                      extra=0, max_num=2, min_num=1,
                                      validate_max=True,
                                      validate_min=True)

When I fill in the top part of the form (caseform) it saves correctly. 当我填写表格(caseform)的顶部时,它可以正确保存。 When I fill in the caseform and a clientform it saves correctly. 当我填写案例表格和客户表格时,它可以正确保存。

If I fill in the caseform but partially fill in the clientform no validation appears to take place, and a case is saved and the client information goes missing and is never saved. 如果我填写个案表格但部分填写了客户表格,则似乎没有进行任何验证,并且案例被保存,客户信息丢失并且永远不会保存。

class CaseCreateView(LoginRequiredMixin, AdviserExistenceMixin,
                 CreateView):
    model = Case
    form_class = CaseForm

    def form_valid(self, form):
        context = self.get_context_data()
        clients = context['clients']
        self.object = form.save()

        if clients.is_valid():
            clients.instance = self.object
            clients.save()
        return super(CaseCreateView, self).form_valid(form)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        if self.request.POST:
            context['clients'] = CaseClientFormset(self.request.POST)
        else:
            context['clients'] = CaseClientFormset()

        context['navbar'] = str(self.model.__name__).lower()
        return context

The other issue I have is that despite specifying min_num=1 and validate_min=True, I appear to be able to save a case without a clientform being filled in. 我遇到的另一个问题是,尽管指定了min_num = 1和validate_min = True,但我似乎能够在不填写客户表格的情况下保存案例。

Any help would be appreciated. 任何帮助,将不胜感激。

Fixed replacing def form_valid with: 修复了将def form_valid替换为:

def form_valid(self, form):
    context = self.get_context_data()
    clients = context['clients']

    if clients.is_valid():
        self.object = form.save()
        clients.instance = self.object
        clients.save()
        return super(CaseUpdateView, self).form_valid(form)
    else:
        return super(CaseUpdateView, self).form_invalid(form)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM