/accounts/register/ NOT NULL 约束处​​的 IntegrityError 失败:accounts_profile.user_id

Posted

技术标签:

【中文标题】/accounts/register/ NOT NULL 约束处​​的 IntegrityError 失败:accounts_profile.user_id【英文标题】:IntegrityError at /accounts/register/ NOT NULL constraint failed: accounts_profile.user_id 【发布时间】:2021-10-23 17:40:18 【问题描述】:

大家好 :) 我尝试在我的应用程序中添加个人资料用户。目标是在创建帐户的同时创建个人资料。但是这个错误来了:

/accounts/register/ 处的 IntegrityError NOT NULL 约束失败:accounts_profile.user_id 我不明白我的代码有什么问题,因为我遵循了一个 youtube 教程,该代码在其中工作..

这是我的代码:

views.py

from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.forms import UserCreationForm
from django.contrib import messages
from .forms import UserForm, ProfileForm
# Create your views here.

def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        profile_form= ProfileForm(request.POST)

        if form.is_valid()  and profile_form.is_valid():
            user = form.save(commit=False)

            profile = profile_form.save(commit=False)
            profile.user = user

            user.save()
            profile.save()

            return redirect('account:login')

    else:
        form = UserCreationForm()
        profile_form = ProfileForm()


    context = 
     'form' : form ,
     'profile': profile_form,
    

    return render(request, 'accounts/register.html', context)

models.py:

from django.db import models
from django.contrib.auth.models import User

# Create your models here.

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
    birthday = models.DateField()
    mail = models.EmailField(max_length=254, null = True, blank = True)


    def __str__(self):
        return self.user.username

forms.py:

from django import forms
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from django.contrib.auth.models import User
from .models import Profile

class LoginForm(AuthenticationForm):
    username= forms.CharField(label='Username', widget=forms.TextInput(attrs='class':'form-control',
    ))
    password= forms.CharField(label='Password', widget=forms.PasswordInput(attrs='class':'form-control',
    ))


class UserForm(UserCreationForm):
    class Meta :
        model = User
        fields =('username','password1', 'password2')

class ProfileForm(forms.ModelForm):
    birthday= forms.DateField(label='birthday',widget=forms.DateInput(attrs=
    'class':'form-control',
    'type' :'date',
    ))

    class Meta :
        model = Profile
        fields =('birthday', 'mail')

【问题讨论】:

【参考方案1】:

如果您得到 DoesNotExist at /accounts/register/ 用户匹配查询不存在。

然后改为这样做:

from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.forms import UserCreationForm
from django.contrib import messages
from .forms import UserForm, ProfileForm
# Create your views here.

def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        profile_form= ProfileForm(request.POST)

        if form.is_valid()  and profile_form.is_valid():

            # Delete commit=False
            user = user_form.save()
            user.save()

            profile = profile_form.save(commit=False)
            profile.user = user

            profile.save()

            return redirect('account:login')

    else:
        form = UserCreationForm()
        profile_form = ProfileForm()


    context = 
     'form' : form ,
     'profile': profile_form,
    

    return render(request, 'accounts/register.html', context)

变化:

user = user_form.save(commit=False)

至:user = user_form.save()

【讨论】:

【参考方案2】:

在您的 views.py 中,您正在创建一个 Profile 对象并在保存 User 对象之前为其提供一个用户

试试这个:

...

if form.is_valid()  and profile_form.is_valid():

            user = form.save()
            
            profile = profile_form.save(commit=False)
            profile.user = user
            profile.save()

            return redirect('account:login')
...

【讨论】:

【参考方案3】:

试试:

from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.forms import UserCreationForm
from django.contrib import messages
from .forms import UserForm, ProfileForm
# Create your views here.

def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        profile_form= ProfileForm(request.POST)

        if form.is_valid()  and profile_form.is_valid():
            user = form.save(commit=False)
            user.save()

            profile = profile_form.save(commit=False)
            profile.user = user

            profile.save()

            return redirect('account:login')

    else:
        form = UserCreationForm()
        profile_form = ProfileForm()


    context = 
     'form' : form ,
     'profile': profile_form,
    

    return render(request, 'accounts/register.html', context)

【讨论】:

以上是关于/accounts/register/ NOT NULL 约束处​​的 IntegrityError 失败:accounts_profile.user_id的主要内容,如果未能解决你的问题,请参考以下文章

/accounts/register 处的 ValueError 必须设置给定的用户名

在 SQL Server 和 ServiceStack.OrmLite 中使用架构名称

在 Bootstrap 3 中为必填字段添加星号

iOS - 根据推送消息进行语音播报