Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NOT NULL constraint failed error

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

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

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:

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

This is my complete 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})
like image 471
AndyJRR Avatar asked Nov 04 '14 04:11

AndyJRR


People also ask

What is NOT NULL constraint failed?

The NOT NULL constraint enforces a column to NOT accept NULL values. This enforces a field to always contain a value, which means that you cannot insert a new record, or update a record without adding a value to this field.

WHAT DOES NOT NULL constraint mean?

The NOT NULL constraint is used to ensure that a given column of a table is never assigned the null value. Once a NOT NULL constraint has been defined for a particular column, any insert or update operation that attempts to place a null value in that column will fail.

How do you use NOT NULL constraint?

NOT NULL constraints make sure that a column does not hold null values, or in other words, NOT NULL constraint make sure that you cannot insert a new record or update a record without entering a value to the specified column(i.e., NOT NULL column). It prevents for acceptance of NULL values.

What does a NULL constraint mean?

Use the NULL keyword to specify that a column can store the NULL value for its data type. This implies that the column need not receive any value during insert or update operations. The NULL constraint is logically equivalent to omitting the NOT NULL constraint from the column definition.


1 Answers

Problem is that user in UserProfile is required, but you are not setting user field in UserProfileForm. The database didn't get user_id, so it tried to set null on this field, but the field had not a 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 you want.

like image 77
Rodbert Avatar answered Oct 26 '22 18:10

Rodbert