1048, "列 'user_id' 不能为空"
Posted
技术标签:
【中文标题】1048, "列 \'user_id\' 不能为空"【英文标题】:1048, "Column 'user_id' cannot be null"1048, "列 'user_id' 不能为空" 【发布时间】:2020-06-12 15:53:01 【问题描述】:models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
fullname = models.CharField(max_length=30,blank=False,null=False)
bio = models.TextField(max_length=500, blank=True)
location = models.CharField(max_length=30, blank=True)
birth_date = models.DateField(null=True, blank=True)
gender = models.CharField(max_length=10,blank=True)
def __str__(self):
return self.fullname
forms.py
class UserForm(forms.ModelForm):
username = forms.CharField(widget=forms.TextInput(attrs='class':'validate','placeholder': 'Enter Username'))
password= forms.CharField(widget=forms.PasswordInput(attrs='placeholder':'Enter Password'))
email=forms.EmailField(widget=forms.TextInput(attrs='placeholder':'Enter Email'))
password2 = None
class Meta:
model=User
fields=['username','password','email']
class ProfileForm(forms.ModelForm):
fullname = forms.CharField(widget=forms.TextInput(attrs='placeholder':'Enter fullname'))
class Meta:
model=Profile
fields=['fullname']
views.py
def register(request):
if request.method =='POST':
form = UserForm(request.POST)
profile_form = ProfileForm(request.POST)
if form.is_valid() and profile_form.is_valid():
variable=form.save(commit=False)
variable.password = pbkdf2_sha256.encrypt(request.POST['password'],rounds=12000,salt_size=32)
variable.save()
profile=profile_form.save(commit=False)
profile.username=variable.username
profile.save()
username = form.cleaned_data.get('username')
messages.success(request,f'account created for username ')
return redirect('login')
else:
form = UserForm()
profile_form = ProfileForm()
context='form':form , 'profile_form':profile_form
return render(request, 'users/register.html',context)
我创建了两个表 auth_user(默认)和 users_profile。当我注册时,用户默认数据进入 auth 表,但全名未插入 user_profile。
【问题讨论】:
【参考方案1】:您没有将profile.user
链接到User
对象。你可以这样做:
def register(request):
if request.method =='POST':
form = UserForm(request.POST)
profile_form = ProfileForm(request.POST)
if form.is_valid() and profile_form.is_valid():
variable=form.save(commit=False)
variable.set_password(variable.password)
variable.save()
profile=profile_form.save(commit=False)
profile.user = variable
profile.save()
username = form.cleaned_data.get('username')
messages.success(request,f'account created for username ')
return redirect('login')
# …
为了设置密码,你最好使用Django的.set_password(..)
method [Django-doc]。
【讨论】:
谢谢!但是我现在无法登录(它说用户名和密码不正确。)我使用的是默认登录 django @RamPatil:您可能不应该自己加密密码。您可以使用.set_password
方法。
(1062, "Duplicate entry '3' for key 2") 全名未插入其他数据库以上是关于1048, "列 'user_id' 不能为空"的主要内容,如果未能解决你的问题,请参考以下文章
完整性约束违规:1048 Column 'user_id' cannot be null 分配角色时发生错误(Laravel 5.3)
Laravel 7 错误 - SQLSTATE [23000]:完整性约束违规:1048 列 'first_name' 不能为空