Django在视图

时间:2017-02-02 17:45:53

标签: django

我可能在这里遗漏了一些非常明显的东西,但是无法让它发挥作用。

我有2个模型(组织和地址),2个表单(每个模型一个)和1个视图,我想用地址作为子项保存组织。

型号:

class Address(models.Model):
    address = models.CharField(max_length=255, verbose_name=_("Address"))
    postal_code = models.CharField(max_length=20, verbose_name=_("Postal_code"))
    city = models.CharField(max_length=255, verbose_name=_("City"))


class Organization(models.Model):
    name = models.CharField(max_length=100, verbose_name=_("Name"))
    address = models.OneToOneField(Address, on_delete=models.CASCADE, verbose_name=_("Address"))

    owner = models.ForeignKey("users.User", related_name="organizations", verbose_name=_("Owner"))

形式:

class AddressForm(forms.ModelForm):
    class Meta:
        model = Address
        fields = ["address", "postal_code", "city"]

    def __init__(self, *args, **kwargs):
        super(AddressForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper(self)
        self.helper.form_tag = False
        self.helper.disable_csrf = True


class OrganizationForm(forms.ModelForm):
    class Meta:
        model = Organization
        fields = ["name", ]

    def __init__(self, *args, **kwargs):
        super(OrganizationForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper(self)
        self.helper.form_tag = False
        self.helper.disable_csrf = True

最后是视图

class OrganizationCreateView(LoginRequiredMixin, TemplateView):
    template_name = "organizations/organization_form.html"

    def get_organization_form(self, data=None):
        return OrganizationForm(data)

    def get_address_form(self, data=None):
        return AddressForm(data)

    def get(self, request, *args, **kwargs):
        ctx = self.get_context_data(organization_form=OrganizationForm(),
                                    address_form=AddressForm())
        return self.render_to_response(ctx)

    def post(self, request, *args, **kwargs):
        organization_form = self.get_organization_form(data=request.POST)
        address_form = self.get_address_form(data=request.POST)

        if organization_form.is_valid() and address_form.is_valid():
            return self.forms_valid(organization_form, address_form)
        return self.forms_invalid(organization_form, address_form)

    def forms_valid(self, organization_form, address_form):
        address = address_form
        address.country = "DE"
        address.save()

        organization = organization_form
        organization.save(commit=False)

        organization.owner = self.request.user
        organization.address = address
        organization.save()

        return redirect("list")

    def forms_invalid(self, organization_form, address_form):
        ctx = self.get_context_data(organization_form=self.get_organization_form(organization_form),
                                    address_form=self.get_address_form(address_form))
        return self.render_to_response(ctx)

所以我保存地址,然后保存组织(使用commit = False),将地址添加到组织,保存组织,并预先设置:异常

Exception Type: IntegrityError at /organizations/create/
Exception Value: null value in column "address_id" violates not-null constraint
DETAIL:  Failing row contains (9, slkdfjlsdfk, lkdjflskdjflsd, , llksjjdlfkjsdlfkjsldkfj, f, null, null, null, null, null, null, null, null, null, null).

正如我已经提到的,它可能是非常明显的,但找不到它。有人可以帮助我吗?

1 个答案:

答案 0 :(得分:2)

您对如何从表单创建模型实例感到有些困惑。该实例从对form.save()的调用返回;它是您需要为其分配地址和用户的实例。

def forms_valid(self, organization_form, address_form):
    address = address_form.save(commit=False)
    address.country = "DE"
    address.save()

    organization = organization_form.save(commit=False)
    organization.owner = self.request.user
    organization.address = address
    organization.save()

    return redirect("list")