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

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

问题描述

我尝试使用Profile Model制作Sign Up表单,然后在模型中进行一些更改。

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

所有表都是在运行<$ c时创建的$ c> manage.py makemigrations ,但是当我要运行manage.py migration时,显示此错误:

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

模型。 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', )


推荐答案

您不能具有默认值= 在外键中,因为它不是用户ID,也不将外键设置为可空的。这就是为什么外键约束失败的原因。

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天全站免登陆