Django2:使用手动方法将实例保存到视图中的模型表单集中的模型中

时间:2018-11-14 17:52:20

标签: django forms

我有一个表单集,可以在视图中创建模型实例。但是,这是很多代码,为了将其分开,我使用手动的类视图方法:

class ClassView(LoginRequiredMixin, GroupRequiredMixin, View):

      template_name = 'form.html'
      form = Form

      get(self, request, *args, **kwargs):

          formset = modelformset_factory(
                Model,
                form=self.form,
                formset=BaseFormSet,
                extra=0,
            )

         self.formset = formset(queryset=qs)


    def post(self, request, *args, **kwargs):

        user = request.user

        formset = modelformset_factory(
                    Model,
                    form=self.formform,
                    formset=BaseCRVFormSet,
                    extra=0,
                )

        if request.POST['submit'] == 'Submit form':

            sample_id = request.POST.get('sample_id')
            obj = Sample.objects.get(
                        id=sample_id
                    )

            formset = formset(request.POST)

            if formset.is_valid():

                for form in formset:
                    self.reportVariant(form)

                self.reportSample(obj, user)



    def reportVariant(self, form):

         crv_obj = form.save(commit=False)
         report = form.clean_report()           

        if report == 'report':

            # Final report for variant
            crv_obj.final_reported = True
            crv_obj.final_report_date = timezone.now()
            crv_obj.final_vasr_id = crv_obj.primary_vasr_id

            crv_obj.primary_vasr_id = None

            crv_obj.save()

        else:
            ...more...


    def reportSample(self, obj, user):

          ... more saving to model ...

我的问题是,我应该在表单类中这样做吗?清理后,在窗体类中额外调用我的方法reportVariant()方法?

0 个答案:

没有答案