我试图在我的注册表格页面上添加另一个包含地址和出生日期的详细信息表格。每次我尝试注册时,都会收到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()