NOT NULL 约束失败:user_profile.user_id [英] NOT NULL constraint failed: user_profile.user_id

查看:28
本文介绍了NOT NULL 约束失败:user_profile.user_id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用配置文件模型制作注册表单,我将对模型进行一些更改.

I'm try to make Sign Up form With Profile Model and I will make some changes in the model.

所有表都是在我运行 manage.py makemigrations 时创建的,但是当我想运行 manage.py migrate 时会显示此错误:

All tables are created when I run manage.py makemigrations but when I want to run manage.py migrate then is show this error:

django.db.utils.IntegrityError: NOT NULL 约束失败:user_profile.user_id

django.db.utils.IntegrityError: NOT NULL constraint failed: 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', )

推荐答案

外键不能有 default="" 因为它不是用户 ID,外键也没有设置为 NULL-有能力的.这就是外键约束失败的原因.

You cannot have default="" in foreign key as it is not User id, also foreign keys is not set to be NULL-able. This is why foreign key constraint fails.

user = models.OneToOneField(User, default=None, null=True, on_delete=models.CASCADE)

这篇关于NOT NULL 约束失败:user_profile.user_id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆