列“user_id”中的Django null值违反非空约束DETAIL:失败行包含

时间:2018-01-04 18:26:13

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

我有以下问题:

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

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})

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

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

粗体回溯部分如下:

    /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)>

2 个答案:

答案 0 :(得分:2)

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

new_profile.user = new_user
new_profile.save()

答案 1 :(得分:0)

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

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})