Skip to content
Advertisement

IntegrityError NOT NULL constraint failed: – in validating form missing user id (foreing key of anothermodel)

Previous title: Unable to import ‘misaka’ – Django

I am following a tutorial about how to build a social network.

I run into this error:

IntegrityError at /posts/new/ NOT NULL constraint failed: posts_post.user_id

Complete traceback (please note the lines in bold):

The above exception (NOT NULL constraint failed: posts_post.user_id) was the direct cause of the following exception:
C:Applicazioni_TommasoPhytonlibsite-packagesdjangocorehandlersexception.py in inner
            response = get_response(request) …
▶ Local vars
C:Applicazioni_TommasoPhytonlibsite-packagesdjangocorehandlersbase.py in _get_response
                response = self.process_exception_by_middleware(e, request) …
▶ Local vars
C:Applicazioni_TommasoPhytonlibsite-packagesdjangocorehandlersbase.py in _get_response
                response = wrapped_callback(request, *callback_args, **callback_kwargs) …
▶ Local vars
C:Applicazioni_TommasoPhytonlibsite-packagesdjangoviewsgenericbase.py in view
            return self.dispatch(request, *args, **kwargs) …
▶ Local vars
C:Applicazioni_TommasoPhytonlibsite-packagesdjangocontribauthmixins.py in dispatch
        return super().dispatch(request, *args, **kwargs) …
▶ Local vars
C:Applicazioni_TommasoPhytonlibsite-packagesdjangoviewsgenericbase.py in dispatch
        return handler(request, *args, **kwargs) …
▶ Local vars
C:Applicazioni_TommasoPhytonlibsite-packagesdjangoviewsgenericedit.py in post
        return super().post(request, *args, **kwargs) …
▶ Local vars
C:Applicazioni_TommasoPhytonlibsite-packagesdjangoviewsgenericedit.py in post
            return self.form_valid(form) …


▶ Local vars
C:UsersTommasoDjango rest frameworkUdemy Djangosimplesocialpostsviews.py in form_valid
        **return super().form_valid(form)** …


▶ Local vars
C:Applicazioni_TommasoPhytonlibsite-packagesdjangoviewsgenericedit.py in form_valid
        self.object = form.save() …
▶ Local vars
C:Applicazioni_TommasoPhytonlibsite-packagesdjangoformsmodels.py in save
            self.instance.save() …


▶ Local vars
C:UsersTommasoDjango rest frameworkUdemy Djangosimplesocialpostsmodels.py in save
        **super().save(*args, **kwargs)** …


▶ Local vars
C:Applicazioni_TommasoPhytonlibsite-packagesdjangodbmodelsbase.py in save
                       force_update=force_update, update_fields=update_fields) …
▶ Local vars
C:Applicazioni_TommasoPhytonlibsite-packagesdjangodbmodelsbase.py in save_base
                force_update, using, update_fields, …
▶ Local vars
C:Applicazioni_TommasoPhytonlibsite-packagesdjangodbmodelsbase.py in _save_table
            result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) …
▶ Local vars
C:Applicazioni_TommasoPhytonlibsite-packagesdjangodbmodelsbase.py in _do_insert
                               using=using, raw=raw) …
▶ Local vars
C:Applicazioni_TommasoPhytonlibsite-packagesdjangodbmodelsmanager.py in manager_method
                return getattr(self.get_queryset(), name)(*args, **kwargs) …
▶ Local vars
C:Applicazioni_TommasoPhytonlibsite-packagesdjangodbmodelsquery.py in _insert
        return query.get_compiler(using=using).execute_sql(return_id) …
▶ Local vars
C:Applicazioni_TommasoPhytonlibsite-packagesdjangodbmodelssqlcompiler.py in execute_sql
                cursor.execute(sql, params) …
▶ Local vars
C:Applicazioni_TommasoPhytonlibsite-packagesdjangodbbackendsutils.py in execute
            return super().execute(sql, params) …
▶ Local vars
C:Applicazioni_TommasoPhytonlibsite-packagesdjangodbbackendsutils.py in execute
        return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) …
▶ Local vars
C:Applicazioni_TommasoPhytonlibsite-packagesdjangodbbackendsutils.py in _execute_with_wrappers
        return executor(sql, params, many, context) …
▶ Local vars
C:Applicazioni_TommasoPhytonlibsite-packagesdjangodbbackendsutils.py in _execute
                return self.cursor.execute(sql, params) …
▶ Local vars
C:Applicazioni_TommasoPhytonlibsite-packagesdjangodbutils.py in __exit__
                raise dj_exc_value.with_traceback(traceback) from exc_value …
▶ Local vars
C:Applicazioni_TommasoPhytonlibsite-packagesdjangodbbackendsutils.py in _execute
                return self.cursor.execute(sql, params) …
▶ Local vars
C:Applicazioni_TommasoPhytonlibsite-packagesdjangodbbackendssqlite3base.py in execute
        return Database.Cursor.execute(self, query, params) …
▶ Local vars

The lines in bold are pointing to these two pieces of code:

1: In my_projectpostsviews.py in form_valid:

def form_valid(self, form):
    self.object = form.save(commit=False)
    self.object = self.request.user
    self.object.save()
    return super().form_valid(form) #<--highligted line 

2: In my_projectpostsmodels.py in save

def save(self, *args, **kwargs):
    self.message_html = m.html(self.message)
    super().save(*args, **kwargs) #<--highligted line 

These functions are run when a user posts a new post inside a group of the social network.

I am using VScode, so I noticed that apparently, my code does not recognise misaka, installed via pip and imported as follows:

import misaka as m

Pylint import error: Unable to import ‘misaka’

I have read misaka documentation but I can’t understand what is wrong.
please note I am using Misaka v. 2.1.0, that apparently does not need to be installed in INSTALLED_APPS in settings.

Any thoughts?

Since it has been suggested that I am trying to create a Post model object into the database without setting the user foreign key, here you can see my my_project/posts/model.py:

from django.db import models
from django.urls import reverse #vho corretto io, ersione di django cambiata
from django.conf import settings

import misaka as m

from groups.models import Group

from django.contrib.auth import get_user_model
User = get_user_model()

class Post(models.Model):
    user = models.ForeignKey(User, related_name="posts", on_delete=models.CASCADE)

    created_at = models.DateTimeField(auto_now=True)
    message = models.TextField()
    message_html = models.TextField(editable=False)

    group = models.ForeignKey(Group, related_name="posts", null=True, blank=True, on_delete=models.CASCADE)

    def __str__(self):
        return self.message

    def save(self, *args, **kwargs):
        self.message_html = m.html(self.message)
        super().save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse('posts:single', kwargs={'username':self.user.username, 'pk':self.pk})

    class Meta:
            ordering = ['-created_at']
            unique_together = ['user', 'message'] 
       

Advertisement

Answer

You’re trying to insert a Post model object into the database without setting the User foreign key.

You should set it to the user object attached to the request first.

def form_valid(self, form):
    form.instance.created_by = self.request.user
    return super().form_valid(form)

Check Django Documentation

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement