Python NOT NULL 约束失败错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26727616/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:57:02  来源:igfitidea点击:

NOT NULL constraint failed error

pythondjangopython-2.7

提问by AndyJRR

I keep getting this error: "NOT NULL constraint failed: users_userprofile.user_id" when I try to submit a form

当我尝试提交表单时,我不断收到此错误:“NOT NULL 约束失败:users_userprofile.user_id”

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

class UserProfile(models.Model):
    #Esta linea es requerira. Linkea UserProfile a un User model
    user = models.OneToOneField(User)

    #atributos adicionales
    about_me = models.TextField(max_length=100,default='',blank=True)
    experience = models.TextField(max_length=250,default='',blank=True)
    offers = models.TextField(max_length=110,default='',blank=True)

This is the forms.py: from django import forms from users.models import UserProfile from django.contrib.auth.models import User

这是forms.py: from django import forms from users.models import UserProfile from django.contrib.auth.models import User

class UserForm(forms.ModelForm):
    password = forms.CharField(min_length=6,label='', widget=forms.PasswordInput(attrs={'placeholder': 'Password','required':'true','class':"form-control"}))
    username = forms.CharField(label='', min_length=6,
                    widget=forms.TextInput(attrs={'placeholder': 'Username','required':'true','class':"form-control",'autofocus':'true'}))
    email = forms.CharField(label='', 
                    widget=forms.TextInput(attrs={'placeholder': 'Email','required':'true','class':"form-control"}))

    class Meta:
        model = User
        fields = ('username', 'email', 'password')

class UserProfileForm(forms.ModelForm):
    about_me = forms.CharField(label='', 
                    widget=forms.Textarea(attrs={'placeholder': 'Sobre mi','required':'true','class':"form-control"}))
    first_name = forms.CharField(label='', 
                    widget=forms.TextInput(attrs={'placeholder': 'Nombre','required':'true','class':"form-control"}))
    last_name = forms.CharField(label='', 
                    widget=forms.TextInput(attrs={'placeholder': 'Apellidos','required':'true','class':"form-control"}))
    experience = forms.CharField(label='', 
                    widget=forms.TextInput(attrs={'placeholder': 'Experiencia','required':'true','class':"form-control"}))
    offers = forms.CharField(label='', 
                    widget=forms.Textarea(attrs={'placeholder': 'Mensaje','required':'true','class':"form-control"}))

    class Meta:
        model = UserProfile
        fields =('first_name','last_name','about_me','experience','offers')

This is the template:

这是模板:

{%extends 'base.html'%}

{%block content%}
{% if user.is_authenticated %}
<h1>Edita tu perfil</h1>
<form id='profile' method='post' action='/edit_profile/'>
{% csrf_token %}

{{profile.as_p}}

<button type='submit'>Editar</button>
</form>
{%endif%}

{%endblock%}

Thanks before hand

提前致谢

EDIT:

编辑:

The error was in the views.py I needed to add an instance to the form, like this:

错误在我需要向表单添加一个实例的 views.py 中,如下所示:

form = UserProfileForm(data=request.POST, instance=profile)

This is my complete views.py:

这是我完整的views.py:

def edit_profile(request):
    try:
        profile = request.user.userprofile

    except UserProfile.DoesNotExist:

        profile = UserProfile(user=request.user)

    if request.method == 'POST':
        form = UserProfileForm(data=request.POST, instance=profile)

        if form.is_valid():

            form.save()

            return HttpResponse("Exito!")
        else:
            form = UserProfileForm(instance=profile)

    else:
        form = UserProfileForm()

    return render(request,
            'editprof.html',
            { 'form': form})

采纳答案by Rodbert

Problem is that user in UserProfile is required, but you are not setting user field in UserProfileForm. Database didn't get user_id, so it tried to set null on this field, but field have not not null constraint. You can set null=True on field definition in UserProfile model, or overwrite save (or probably is_valid) form method to set user automatically, or add user field to UserProfileForm, or whatever what you want.

问题是 UserProfile 中的用户是必需的,但您没有在 UserProfileForm 中设置用户字段。数据库没有得到user_id,所以它试图在这个字段上设置为空,但该字段没有非空约束。您可以在 UserProfile 模型中的字段定义上设置 null=True,或覆盖保存(或可能是 is_valid)表单方法以自动设置用户,或将用户字段添加到 UserProfileForm,或任何您想要的。