简体   繁体   中英

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. 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.

Any help would be appreciated.

Fixed replacing def form_valid with:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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