一个html表单,几个相互关联的django表单 - 如何保存?

时间:2015-05-19 15:24:09

标签: python django forms

有一个问题,我需要提交两个相互关联的模型与一个html表单。我知道如何提交两个单独的表单,但外键让我疯狂相关的模型。

问题是,第二个表单应该从第一个表单填充带有外键的字段。

在这个特殊情况下,我决定合并两个模型,但我认为应该有一些案例,其中描述问题的解决方法会很有用。

请考虑以下代码:

模型:

from django.db import models

class Facility(models.Model):
    name = models.CharField(max_length=255)

class FacilityDetail(models.Model):
    some_details = models.CharField(max_length=255)
    facility = models.ForeignKey(Facility)

对应的django形式:

from django import forms

class FacilityForm(forms.ModelForm):

    class Meta:
        model = Facility
        fields = ('name')

class FacilityDetailForm(forms.ModelForm):

    class Meta:
        model = FacilityDetail
        fields = ('some_details', 'facility')

处理表单的视图:

from django.views.generic import View

FACILITY_PREFIX = 'facility'
FACILITY_DETAIL_PREFIX = 'facility_detail'

class FacilityCreateView(View):

    def get(self, request, *args, **kwargs):
        facility_form = FacilityForm(prefix=FACILITY_PREFIX)
        facility_detail_form = FacilityDetailForm(prefix=FACILITY_DETAIL_PREFIX)

        context = {
            'facility_form': facility_form,
            'facility_detail_form': facility_detail_form,
        }

        return render(request, 'facility_create.html', context)

    def post(self, request, *args, **kwargs):
        facility_form = FacilityForm(request.POST, prefix=FACILITY_PREFIX)
        facility_detail_form = FacilityDetailForm(request.POST, prefix=FACILITY_DETAIL_PREFIX)

        if facility_form.is_valid():
            facility = facility_form.save()

            # is not valid, because there is no `facility`
            if facility_detail_form.is_valid():
                facility_detail_form.cleaned_data['facility'] = facility

                facility_detail_form.save()

                return redirect(...)

        context = {
            'facility_form': facility_form,
            'facility_detail_form': facility_detail_form,
        }

        return render(response, 'facility_list.html', context)

我应该如何处理表格验证并保存在FacilityCreateView.post

1 个答案:

答案 0 :(得分:2)

解决这个问题的一种方法是:

facility_detail_form.cleaned_data['facility'] = facility

可以替换为:

facility_detail = facility_detail_form.save(commit=False)
facility_detail.facility = facility
facility_detail.save()

#rest of the code.. .

这里为commit=False creates对象,而不将其保存到数据库,您可以在保存之前分配外键对象。