Django->;异常值:(1048,“列';用户id';不能为空”
我有以下观点,效果很好:Django->;异常值:(1048,“列';用户id';不能为空”,django,django-models,Django,Django Models,我有以下观点,效果很好: @transaction.atomic def register(request): next_url = request.POST.get('next', request.GET.get('next', reverse('profile'))) if request.method == 'POST': form = RegistrationForm(request.POST) profileform = ProfileF
@transaction.atomic
def register(request):
next_url = request.POST.get('next', request.GET.get('next', reverse('profile')))
if request.method == 'POST':
form = RegistrationForm(request.POST)
profileform = ProfileForm(request.POST)
if form.is_valid() and profileform.is_valid():
new_user = form.save()
# Login the newly created user.
authenticated_user = authenticate(username=new_user.username,
password=form.cleaned_data['password1'])
login(request, authenticated_user)
return redirect(next_url)
else:
form = RegistrationForm()
profileform = ProfileForm()
return render(request, 'meta/register.html', {'form': form, 'profileform': profileform, 'next': next_url})
但是,当我希望使用以下行(位于new_user=form.save()行下方)保存其他配置文件信息时:
我得到以下错误:
Exception Type: IntegrityError
Exception Value: (1048, "Column 'user_id' cannot be null")
我的个人资料模型如下:
class Profile(models.Model):
user = models.OneToOneField(User)
dob = models.DateField(max_length=8)
class Meta:
managed = True
db_table = 'fbf_profile'
任何帮助都会很好,Alan。显然,
配置文件表单中没有设置用户
字段。配置文件
模型需要用户
的用户id
ProfileForm
需要一个您必须设置的user
字段,或者您必须在ProfileForm
的save()
函数中手动设置user
字段(然后您必须覆盖该字段)。显然ProfileForm
中没有设置user
字段。配置文件
模型需要用户
的用户id
ProfileForm
需要一个您必须设置的user
字段,或者您必须在ProfileForm
的save()
函数中手动设置user
字段(然后您必须覆盖该字段).当使用这样的外键时,通常会看到使用commit=False进行保存,然后在模型上手动设置外键。e、 g
new_user = form.save()
profile = profileform.save(commit=False)
if profile.user_id is None:
profile.user_id = new_user.id
profile.save()
此save()
方法接受可选的commit
关键字参数,该参数接受True
或False
。如果使用commit=False
调用save()
,则它将返回一个尚未保存到数据库的对象。在这种情况下,您可以对生成的模型实例调用save()
。如果要在保存对象之前对其进行自定义处理,或者要使用某个专用模型保存选项,则此选项非常有用<默认情况下,code>commit
为True
当使用这样的外键时,通常会看到使用commit=False进行保存,然后在模型上手动设置外键。e、 g
new_user = form.save()
profile = profileform.save(commit=False)
if profile.user_id is None:
profile.user_id = new_user.id
profile.save()
此save()
方法接受可选的commit
关键字参数,该参数接受True
或False
。如果使用commit=False
调用save()
,则它将返回一个尚未保存到数据库的对象。在这种情况下,您可以对生成的模型实例调用save()
。如果要在保存对象之前对其进行自定义处理,或者要使用某个专用模型保存选项,则此选项非常有用<默认情况下,code>commit
为True
谢谢你的解释和答案。帮助旧知识库。谢谢你的解释和答案。帮助旧知识库。