django multiple forms with formsets

喜你入骨 提交于 2019-12-01 01:55:57

https://docs.djangoproject.com/en/dev/ref/forms/models/#django.forms.models.inlineformset_factory

from django.core.urlresolvers import reverse
from django.forms.models import inlineformset_factory

TimingFormSet = inlineformset_factory(HospitalDoctor, Timing, form=TimingForm, extra=7)

class HospitalDoctorAddView(CreateView):
   ...

    def get_context_data(self, **kwargs):
        context = super(HospitalDoctorAddView, self).get_context_data(**kwargs)
        context['formset'] = TimingFormSet(instance=Timing())

        return context

    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST)
        formset = TimingFormSet(request.POST, request.FILES)  # request.FILES for files, remove if don't send files

        if form.is_valid() and formset.is_valid():
            return self.form_valid(form, formset)
        else:
            return self.form_invalid(form, formset)

    def form_valid(self, form, formset):
        self.object = form.save()
        formset.instance = self.object
        formset.save()

        return HttpResponseRedirect(self.get_success_url())

    def form_invalid(self, form, formset):
        return self.render_to_response(
            self.get_context_data(
                form=form,
                formset=formset
            )
        )

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