【问题标题】:Django null value in column "user_id" violates not-null constraint DETAIL: Failing row contains“user_id”列中的 Django 空值违反非空约束细节:失败行包含
【发布时间】:2018-01-04 18:26:12
【问题描述】:

我有以下问题:

我正在尝试保存用户和个人资料,但是当我尝试在我的数据库中发布时出现以下错误:

null value in column "user_id" violates not-null constraint
DETAIL:  Failing row contains (16, 2018-01-01 00:00:00+00, null, colegio monserrat, femenino, null, primero, social, null, null, null, null, null, null, null, null, null, null, Ciencias mundo contemporáneo, Historia de la filosofía, Lengua catalana y literatura I, Lengua catalana y literatura II, Lengua extranjera I, Lengua extranjera II, Lengua castellana y literatura I, Lengua castellana y literatura II, fisica, matematicas, quimica, matematicas, matematicas, matematicas, matematicas, fisica, Educación física, Filosofía, null, Historia).

我的模型如下:

class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
birth_date = models.DateTimeField(null=True, blank=True)
sex = models.CharField(null=True, max_length=50, choices=SEX_CHOICES)
school = models.CharField(null=True, max_length=50, choices=SCHOOL_CHOICES)
schoolCode = models.IntegerField(null=True)
bachelorCourse = models.CharField(null=True, max_length=50, choices=COURSE_CHOICES)
bachelorModality = models.CharField(null=True, max_length=50, choices=COURSE_MODALITY_CHOICES)

password = models.CharField(null=True, max_length=50)
password2 = models.CharField(null=True, max_length=50)

obligatorySubjectOne1 = models.CharField(null=True, max_length=100, default='Lengua catalana y literatura I')
obligatorySubjectTwo1 = models.CharField(null=True, max_length=100, default='Lengua castellana y literatura I')
obligatorySubjectThree1 = models.CharField(null=True, max_length=100, default='Lengua extranjera I')
obligatorySubjectFour1 = models.CharField(null=True, max_length=100, default='Ciencias mundo contemporáneo')
obligatorySubjectFive1 = models.CharField(null=True, max_length=100, default='Educación física')
obligatorySubjectSix1 = models.CharField(null=True, max_length=100, default='Filosofía')

optionalSubjectOne1 = models.CharField(null=True, max_length=100, choices=SUBJECTS_CHOICES_OPTIONALLY)
optionalSubjectTwo1 = models.CharField(null=True, max_length=100, choices=SUBJECTS_CHOICES_OPTIONALLY)
optionalSubjectThree1 = models.CharField(null=True, max_length=100, choices=SUBJECTS_CHOICES_OPTIONALLY)
optionalSubjectFour1 = models.CharField(null=True, max_length=100, choices=SUBJECTS_CHOICES_OPTIONALLY)

obligatorySubjectOne2 = models.CharField(null=True, max_length=100, default='Lengua catalana y literatura II')
obligatorySubjectTwo2 = models.CharField(null=True, max_length=100, default='Lengua castellana y literatura II')
obligatorySubjectThree2 = models.CharField(null=True, max_length=100, default='Lengua extranjera II')
obligatorySubjectFour2 = models.CharField(null=True, max_length=100, default='Historia de la filosofía')
obligatorySubjectFive2 = models.CharField(null=True, max_length=100, default='Historia')

optionalSubjectOne2 = models.CharField(null=True, max_length=100, choices=SUBJECTS_CHOICES_OPTIONALLY)
optionalSubjectTwo2 = models.CharField(null=True, max_length=100, choices=SUBJECTS_CHOICES_OPTIONALLY)
optionalSubjectThree2 = models.CharField(null=True, max_length=100, choices=SUBJECTS_CHOICES_OPTIONALLY)
optionalSubjectFour2 = models.CharField(null=True, max_length=100, choices=SUBJECTS_CHOICES_OPTIONALLY)
optionalSubjectFive2 = models.CharField(null=True, max_length=100, choices=SUBJECTS_CHOICES_OPTIONALLY)

avatarChoose = models.CharField(null=True, max_length=50)  # imageField
interest = models.CharField(null=True, max_length=50, choices=SUBJECTS_CHOICES_OPTIONALLY)
interestOne = models.CharField(null=True, max_length=50, choices=SUBJECTS_CHOICES_OPTIONALLY)
interestTwo = models.CharField(null=True, max_length=50, choices=SUBJECTS_CHOICES_OPTIONALLY)
university = models.CharField(null=True, max_length=50, choices=SUBJECTS_CHOICES_OPTIONALLY)
universityOne = models.CharField(null=True, max_length=50, choices=SUBJECTS_CHOICES_OPTIONALLY)
universityTwo = models.CharField(null=True, max_length=50, choices=SUBJECTS_CHOICES_OPTIONALLY)
meanCourse = models.FloatField(null=True)

forms.py中的ModelForm如下:

class UserEditForm(forms.ModelForm):
class Meta:
    model = User
    fields = ('first_name', 'last_name', 'email')
    labels = {
        "first_name": "Nombre",
        "last_name": "Apellidos",
        "email": "Correo"
    }

    widgets = {
        "first_name": forms.TextInput(attrs={'class': 'form-control'}),
        "last_name": forms.TextInput(attrs={'class': 'form-control'}),
        "email": forms.TextInput(attrs={'class': 'form-control'})
    }


# build the some edit profile register variables
class ProfileEditForm(forms.ModelForm):
    class Meta:
        model = Profile
        Profile.obligatorySubjectOne1 = "Castellano"
        Profile.obligatorySubjectFive1 = "Castellano"

        fields = ('birth_date',
                  'sex',
                  'school',
                  'bachelorCourse',
                  'bachelorModality',
                  'optionalSubjectOne1',
                  'optionalSubjectTwo1',
                  'optionalSubjectThree1',
                  'optionalSubjectFour1',
                  'optionalSubjectOne2',
                  'optionalSubjectTwo2',
                  'optionalSubjectThree2',
                  'optionalSubjectFour2'
                  )
        labels = {
            "birth_date": "Fecha de nacimiento",
            "sex": "Sexo",
            "school": "Escuela",
            "bachelorCourse": "Curso de bachillerato",
            "bachelorModality": "Modalidad de bachillerato",
            "optionalSubjectOne1": "Escojer Optativa 1B",
            "optionalSubjectTwo1": "Escojer Optativa 1B",
            "optionalSubjectThree1": "Escojer Optativa 1B",
            "optionalSubjectFour1": "Escojer Optativa 1B",
            "optionalSubjectOne2": "Escojer Optativa 2B",
            "optionalSubjectTwo2": "Escojer Optativa 2B",
            "optionalSubjectThree2": "Escojer Optativa 2B",
            "optionalSubjectFour2": "Escojer Optativa 2B"
        }
        widgets = {
            "birth_date": forms.SelectDateWidget(empty_label=("Choose Year", "Choose Month", "Choose Day")),
            "bachelorCourse": forms.Select(attrs={'class': 'select'}),
            "bachelorModality": forms.Select(attrs={'class': 'select'}),
            "optionalSubjectOne1": forms.Select(attrs={'class': 'select'}),
            "optionalSubjectTwo1": forms.Select(attrs={'class': 'select'}),
            "optionalSubjectThree1": forms.Select(attrs={'class': 'select'}),
            "optionalSubjectFour1": forms.Select(attrs={'class': 'select'}),
            "optionalSubjectOne2": forms.Select(attrs={'class': 'select'}),
            "optionalSubjectTwo2": forms.Select(attrs={'class': 'select'}),
            "optionalSubjectThree2": forms.Select(attrs={'class': 'select'}),
            "optionalSubjectFour2": forms.Select(attrs={'class': 'select'})
        }

最后我保存创建的对象的视图如下:

def register(request):
if request.method == 'POST':
    user_form = UserRegistrationForm(request.POST)
    profile_form = ProfileEditForm(request.POST)
    if user_form.is_valid() and profile_form.is_valid():
        # Create a new user object but avoid saving it yet
        new_user = user_form.save(commit=False)
        new_profile = profile_form.save(commit=False)
        # Set the chosen password
        new_user.set_password(user_form.cleaned_data['password'])
        # Save the User object
        new_user.save()
        new_profile.save()

        return render(request, 'account/register_done.html', {'new_user': user_form, 'new_profile': profile_form})
else:
    user_form = UserRegistrationForm()
    profile_form = ProfileEditForm()
    return render(request, 'account/register.html', {'user_form': user_form, 'profile_form': profile_form})

这是我认为您需要它来了解问题的所有代码。之前,我的代码的注册部分,它工作正常,我不知道问题是否可能是数据库引起的,或者为什么不是所有的指令都在视图中。

如果您能帮助我,请提前感谢您。

traceback的粗体部分如下:

    /home/web_unithinks/unithinks/account/views.py in register
            new_profile.save() ...
▼ Local vars
Variable    Value
new_profile 
<Profile: Profile for user verver>
new_user    
<User: verver>
profile_form    
<ProfileEditForm bound=True, valid=True, fields=(birth_date;sex;school;bachelorCourse;bachelorModality;optionalSubjectOne1;optionalSubjectTwo1;optionalSubjectThree1;optionalSubjectFour1;optionalSubjectOne2;optionalSubjectTwo2;optionalSubjectThree2;optionalSubjectFour2)>
request 
<WSGIRequest: POST '/account/register/'>
user_form   
<UserRegistrationForm bound=True, valid=True, fields=(username;email;first_name;last_name;password;password2)>

【问题讨论】:

  • 顺便说一句,Profile.obligatorySubjectOne1 = "Castellano"Profile.obligatorySubjectFive1 = "Castellano" 行看起来不正确。目前尚不清楚您要在那里做什么。我会删除这些行。
  • 是的,我在做证明的时候放的。

标签: django django-models django-forms django-views


【解决方案1】:

你需要在保存之前设置new_profile.user

new_profile.user = new_user
new_profile.save()

【讨论】:

  • 如果您仍然收到错误,请确保您已保存代码并在进行任何更改后重新启动服务器,然后使用您当前的代码更新您的问题。
  • 我确定我已经保存了代码并重新启动了服务器。错误是一样的,错误信息没有改变。
  • 那我帮不上忙,因为如果您在保存之前设置new_profile.user,您显示的代码不应该给出该错误。完整的回溯可能会提供一些关于错误发生原因的线索。
  • 是的,我修改错误并添加回溯的粗体部分
  • 这不是完整的追溯。使用按钮切换格式以便于复制/粘贴,然后包含完整的回溯。此外,更新您的问题以显示您当前的代码。
【解决方案2】:

您的个人资料对象需要在保存之前关联一个用户,这类似于

def register(request):
    if request.method == 'POST':
        user_form = UserRegistrationForm(request.POST)
        profile_form = ProfileEditForm(request.POST)
        if user_form.is_valid() and profile_form.is_valid():
            # Create a new user object but avoid saving it yet
            new_user = user_form.save(commit=False)
            new_profile = profile_form.save(commit=False)
            # Set the chosen password
            new_user.set_password(user_form.cleaned_data['password'])
            # Save the User object
            new_user.save()
            #####################
            #SOMETHING LIKE THIS#
            #####################
            new_profile.user = new_user
            new_profile.save()

            return render(request, 'account/register_done.html', {'new_user': user_form, 'new_profile': profile_form})
    else:
        user_form = UserRegistrationForm()
        profile_form = ProfileEditForm()
        return render(request, 'account/register.html', {'user_form': user_form, 'profile_form': profile_form})

【讨论】:

  • 您可能需要重新同步用户模型
  • 是否存在任何重新同步用户的命令?还是您指的是删除我的迁移并重新进行迁移?
猜你喜欢
  • 2021-03-30
  • 1970-01-01
  • 1970-01-01
  • 2016-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-28
  • 2018-09-12
相关资源
最近更新 更多