gpt4 book ai didi

python - 完整性错误 : NOT NULL constraint failed: core_userprofile. 用户 ID

转载 作者:太空宇宙 更新时间:2023-11-03 15:01:06 28 4
gpt4 key购买 nike

我正在尝试通过 django 制作一个简单的注册/登录页面。我使用了 UserCreationForm 并使用模型 UserProfile 来扩展用户模型。当我尝试保存注册的发布请求时,它给出了完整性错误。我是 django 新手,所以简短的解释将不胜感激。提前致谢

表单.py

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from mysite.core.models import UserProfile
from django.db import models

class SignUpForm(UserCreationForm):
first_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
department = forms.CharField(max_length=30)
last_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.')

class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email','password1', 'password2', 'department',)

def save(self, commit=True):
# Save the provided password in hashed format
user = super(SignUpForm, self).save(commit=False)
user_profile = UserProfile(user=user, department=self.cleaned_data['department'])
user.save()
user_profile.save()
return user, user_profile

View .py

from django.contrib.auth.decorators import login_required
from django.contrib.auth import login, authenticate
from django.shortcuts import render, redirect
from mysite.core.forms import SignUpForm

@login_required
def home(request):
return render(request, 'home.html')

def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
user,user_profile = form.save(commit=False)
username = user.cleaned_data.get('username')
raw_password = user.cleaned_data.get('password1')
user = authenticate(username=username, password=raw_password)
login(request, user)
return redirect('home')
else:
form = SignUpForm()
return render(request, 'signup.html', {'form': form})

模型.py

from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE,unique=True)
department = models.CharField(max_length=500, blank=True)

最佳答案

您必须先保存用户,然后才能将其分配给用户配置文件。

user = super(SignUpForm, self).save(commit=False)
user.save()
user_profile = UserProfile(user=user, department=self.cleaned_data['department'])

在表单的 save() 方法中创建 useruser_profile 有点令人困惑。您的方法不再遵循 commit 标志,因为它始终保存用户和用户配置文件。最好将创建配置文件的代码移动到 View 中的 if form.is_valid() block 中。

关于python - 完整性错误 : NOT NULL constraint failed: core_userprofile. 用户 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45100437/

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