一个CreateView中的两个ModelForms

时间:2017-09-26 12:40:49

标签: python django

这可能没有任何意义,但最好能够获得如何正确实施此行为的建议 我有User模型和另外两个模型(让它为AB)。 AB都有ForeignKeyUser。在User创建时,我还为此用户创建AB

def save(self, *args,  **kwargs):
    user_id = self.id
    super(User, self).save(*args, **kwargs)
    if user_id is None:
        as_A = A(user=self)
        as_A.save()
        as_B = B(user=self)
        as_B.save()

AB中唯一必填字段为user = models.OneToOneField(User),其他字段为可选字段。

class A(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    x = models.CharField(max_length=100, blank=True)

class B(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    y = models.CharField(max_length=100, blank=True)

我想提供两种注册表单:作为A或B.在注册表单中A,客户应该能够为与A相关的User模型实体设置字段。与B类似。

这是我的RegistrationForm

class RegistrationForm(forms.ModelForm):
    password = forms.CharField(
        strip=False,
        widget=forms.PasswordInput,
    )
    confirm_password = forms.CharField(
        strip=False,
        widget=forms.PasswordInput
    )

    class Meta:
        model = User
        fields = ['email', 'first_name', 'password']

    def clean(self):
        cleaned_data = super(RegistrationForm, self).clean()
        password = cleaned_data.get("password")
        confirm_password = cleaned_data.get("confirm_password")
        if password != confirm_password:
            raise forms.ValidationError("Passwords are not same")
        return cleaned_data

如您所见,它只包含User个字段。

如何正确实施其他表单和视图?

1 个答案:

答案 0 :(得分:1)

使用MultiModelForm中的django-betterforms。这将帮助您实现您想要的目标。

相关问题