gpt4 book ai didi

python - 1048, "Column ' user_id' 不能为空"

转载 作者:行者123 更新时间:2023-12-04 10:30:08 25 4
gpt4 key购买 nike

模型.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

表格.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']

View .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 中。

最佳答案

您没有链接 profile.userUser目的。你可以这样做:

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] .

关于python - 1048, "Column ' user_id' 不能为空",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60453485/

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