Home > front end >  NOT NULL constraint failed: tasks_task.user_id
NOT NULL constraint failed: tasks_task.user_id

Time:02-02

I'm working on a Django project using Python3. I have this error come ups when I'm trying to create a new task.

django.db.utils.IntegrityError: NOT NULL constraint failed: tasks_task.user_id

The web application works fine, but when I try to create a new task is when the error occurs, I have read all the posts related to the problem, but I have not found the solution.

I tried to update my sqlite3, but it didn't work.

This is my code

from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.db import IntegrityError
from .forms import TaskForm


def home(request):
    return render(request, 'home.html')

# Create your views here.


def signup(request):

    if request.method == 'GET':
        return render(request, 'signup.html', {
            'form': UserCreationForm
        })
    else:
        if request.POST['password1'] == request.POST['password2']:
            try:
                user = User.objects.create_user(
                    username=request.POST['username'], password=request.POST['password1'])
                user.save()
                login(request, user)
                return redirect('tasks')

            except IntegrityError:
                return render(request, 'signup.html', {
                    'form': UserCreationForm,
                    'error': 'Username already taken'
                })

        return render(request, 'signup.html', {
            'form': UserCreationForm,
            'error': 'Passwords did not match'
        })


def tasks(request):
    return render(request, 'tasks.html')


def create_task(request):
    if request.method == 'GET':
        return render(request, 'create_task.html', {
            'form': TaskForm,
        })
    else:
        try:
         form = TaskForm(request.POST)
         new_task = form.save(commit=False)
         new_task.User = request.user
         new_task.save()
         return redirect('tasks')
        except ValueError:
         return render(request, 'create_task.html', {
            'form': TaskForm,
            'error': 'Bad data passed in. Try again.'
        })


def signout(request):
    logout(request)
    return redirect('home')


def signin(request):
    if request.method == 'GET':
        return render(request, 'signin.html', {
            'form': AuthenticationForm
        })
    else:
        user = authenticate(
            request, username=request.POST['username'], password=request.POST['password'])
        if user is None:
            return render(request, 'signin.html', {
                'form': AuthenticationForm,
                'error': 'Username and password did not match'
            })
        else:
            login(request, user)
            return redirect('tasks')

Here's my models.py


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

# Create your models here.


class Task(models.Model):
    title = models.CharField(max_length=200)
    description = models.TextField(blank=True)
    created = models.DateTimeField(auto_now_add=True)
    datecompleted = models.DateTimeField(null=True, blank=True)
    important = models.BooleanField(default=False)
    user = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.title   ' | '   str(self.user)

CodePudding user response:

You seem to be using the wrong attribute name when setting the user. Note that all Python attributes are case sensitive:

class Task(models.Model):
    ...
    user = models.ForeignKey(User, on_delete=models.CASCADE)

but

new_task.User = request.user

Changing it to new_task.user should solve the problem.

  • Related