我尝试在我的注册表页面上添加另一个包含地址和出生日期的详细信息表单。每次我尝试注册时,我都会收到 NOT NULL 约束失败错误。
models.py
class Details(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
address = models.CharField(max_length=60, blank=True)
birth_date = models.DateField(null=True, blank=True)
views.py
def register(request):
if request.method == 'POST':
r_form = UserRegisterForm(request.POST)
o_form = DetailsForm(request.POST)
if r_form.is_valid and o_form.is_valid():
r_form.save()
o_form.save()
username = r_form.cleaned_data.get('username')
messages.success(request, f'Your account has been created!')
return redirect('login')
else:
r_form = UserRegisterForm()
o_form = DetailsForm()
context = {
'r_form' : r_form,
'o_form' : o_form
}
return render(request, 'users/register.html', context)
forms.py
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email','password1', 'password2']
class DetailsForm(forms.ModelForm):
address = forms.CharField()
birth_date = forms.DateField()
class Meta:
model = Details
fields = ['address', 'birth_date']
错误
虽然自可插拔用户模型出现以来,无关的详细信息/配置文件"sidecar"模型不是最佳实践,但此特定问题是由两个模型未关联引起的。
尝试
if r_form.is_valid and o_form.is_valid():
user = r_form.save()
o_form.instance.user = user
o_form.save()