Database NOT NULL constraint failed Django error

I want an option to show which user adds a book to my website and I checked that the user is signed up but I got this error.

Models:

class Books(models.Model):
    user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
    title = models.CharField(max_length=150)
    author = models.CharField(max_length=150)
    description = models.TextField()
    price = models.DecimalField(max_digits=5, decimal_places=2)
    book_cover = models.ImageField(upload_to='books  covers/', blank=True)

    def __str__(self):
        return f'{self.title} by {self.author}.'

    def get_absolute_url(self):
        return reverse('book_detail', args=[self.id])

Views:

class AddBook(LoginRequiredMixin, generic.CreateView):
    model = Books
    form_class = AddBookForm
    template_name = 'books/add_book.html'

I got that error...:

IntegrityError at /books/add_book/
NOT NULL constraint failed: books_books.user_id

The problem originates from the Books model class, specifically with the ForeignKey field user. By default, Django requires a ForeignKey field to have a value; it cannot be NULL. In your AddBook view class, when a book instance is being created, the user field is inadvertently left as NULL, which violates the database's NOT NULL constraint for that field.

To fix this issue you need to override the form_valid method in your AddBook class to include the current user's information as the value for the user field like this:

Views:

class AddBook(LoginRequiredMixin, generic.CreateView):
    model = Books
    form_class = AddBookForm
    template_name = 'books/add_book.html'

    def form_valid(self, form):
        form.instance.user = self.request.user # Fetch and assign the logged in user as user
        return super().form_valid(form)

This will fix database NOT NULL constraint issue you are having.

Back to Top