gpt4 book ai didi

python - 一个 CreateView 中的两个 ModelForm

转载 作者:太空宇宙 更新时间:2023-11-03 14:43:29 25 4
gpt4 key购买 nike

这可能没有意义,但最好获取如何正确实现此行为的建议。
我有 User 模型和另外两个模型(让它成为 AB)。 AB 都有 ForeignKeyUser。在创建用户时,我还为此用户创建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 模型实体相关字段设置字段到用户。与 B 类似。

这是我的注册表格:

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字段。

如何正确实现附加表单和 View ?

最佳答案

使用MultiModelForm来自django-betterforms 。这将帮助您实现您想做的事情。

关于python - 一个 CreateView 中的两个 ModelForm,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46426865/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com