NOT NULL约束失败错误

时间:2014-11-04 04:09:25

标签: python django python-2.7

我一直收到这个错误:" 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)

这是forms.py:     来自django进口表格     来自users.models导入UserProfile     来自django.contrib.auth.models导入用户

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

这是模板:

{%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%}

先谢谢

编辑:

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

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

这是我完整的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})

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:0)

在模型中提供一个空值

    user = models.OneToOneField(User, null=True)
    about_me = models.TextField(max_length=100,default='',blank=True, null=True)
    experience = models.TextField(max_length=250,default='',blank=True, null=True)
    offers = models.TextField(max_length=110,default='',blank=True, null=True)