我尝试使用Profile Model制作注册表单,我将在模型中进行一些更改。
我运行manage.py makemigrations
时会创建所有表,但是当我想运行manage.py migrate时,会显示此错误:
django.db.utils.IntegrityError:NOT NULL约束失败: user_profile.user_id
Model.py
class Profile(models.Model):
user = models.OneToOneField(User,default="", on_delete=models.CASCADE)
bio = models.TextField(max_length=500, blank=True)
location = models.CharField(max_length=30, blank=True)
birth_date = models.DateField(null=True, blank=True)
@receiver(post_save, sender=User)
def update_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
instance.profile.save()
Views.py :
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
user.refresh_from_db()
user.profile.birth_date = form.cleaned_data.get('birth_date')
raw_password = form.cleaned_data.get('password1')
user.save()
user = authenticate(username=user.username, password=raw_password)
login(request, user)
return redirect('home')
else:
form = SignUpForm()
return render(request, 'signup.html', {'form': form})
form.py :
class SignUpForm(UserCreationForm):
birth_date = forms.DateField(help_text='Required. Format: YYYY-MM-DD')
class Meta:
model = User
fields = ('username', 'birth_date', 'password1', 'password2', )
答案 0 :(得分:0)
外键中不能有default=""
因为它不是用户ID,外键也不能设置为NULL。这就是外键约束失败的原因。
user = models.OneToOneField(User, default=None, null=True, on_delete=models.CASCADE)
答案 1 :(得分:0)
您必须将pk值设置为等于user_id
(user_id=pk
)(此处pk与用户模型有关),您可以在View.py中设置