gpt4 book ai didi

python - 表单集、外键和 OneToOne

转载 作者:太空宇宙 更新时间:2023-11-03 18:17:59 27 4
gpt4 key购买 nike

我想在不使用任何外部应用程序的情况下创建注册表单,但我无法保存foregin和OneToOne与表单集的关系。这是我的 models.py :

class UserProfile(models.Model):
user = models.OneToOneField(User)
avatar = models.ImageField(null=True, blank=True, upload_to='avatar/')
website = models.URLField(null=True, blank=True)
birthday = models.DateField()
country = CountryField()

GENDER_CHOICES = (
('M', 'Male'),
('F', 'Female'),
)
gender = models.CharField(max_length=1, choices=GENDER_CHOICES)

def __str__(self):
return "UserProfile(models)"


class UserLanguage(models.Model):
user = models.ForeignKey(User)
language = models.CharField(max_length=7, choices=LANGUAGES)
level = models.CharField(max_length=1)
# http://stackoverflow.com/questions/3201018/django-language-codes

def __str__(self):
return "UserLanguage(models)"

这是我的 forms.py :

class RegisterForm(forms.ModelForm):
class Meta:
model = User
fields = ('username', 'password',)
exclude = ('last_login',)
widgets = {'password': forms.PasswordInput(), }


UserProfileFormSet = inlineformset_factory(User, UserProfile, can_delete=False)
UserLanguageFormSet = inlineformset_factory(User, UserLanguage, can_delete=False, extra=1)

还有我的views.py:

def registration(request):
if request.method == "POST":
user = RegisterForm(request.POST)
user_profile = UserProfileFormSet(request.POST)
user_language = UserLanguageFormSet(request.POST)

if user.is_valid() and user_profile.is_valid() and user_language.is_valid():
u = user.save()

user_profile.user = u
user_profile.save()

user_language.user = u
user_language.save()

else:
user = RegisterForm()
user_profile = UserProfileFormSet()
user_language = UserLanguageFormSet()

return render(request, 'user/registration.html', locals())

我收到此错误:

Column 'user_id' cannot be null

我可以做什么来解决我的问题?您还有其他意见吗?谢谢。

最佳答案

您对表单集 user_profileuser_language 的命名令人困惑。但它们不是配置文件或语言对象,它们是表单集,因此设置其用户属性将不起作用。

这有效:

for profile_form in user_profile.forms:
up = profile_form.save(commit=False)
up.user = u
up.save()

for language_form in user_language.forms:
ul = language_form.save(commit=False)
ul.user = u
ul.save()

但实际上你应该按事物的本质命名。

关于python - 表单集、外键和 OneToOne,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24685079/

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