Yucehan Kucukmotor
Yucehan Kucukmotor

Reputation: 67

I get 'django.db.utils.IntegrityError: null value in column "user_id" violates not-null constraint' when I try to publish a new post

--This is my first ever question on StackOverflow. So if I violate any community rules/standards, I apologize. Though there are similar questions around, no answer helped me solve the problem I am encountering. I would say I am not good enough a programmer to figure out the solution---

When I hit publish to add a new post, I get the following error

"django.db.utils.IntegrityError: null value in column "user_id" violates not-null constraint DETAIL: Failing row contains (18, s, s, 2019-05-26 15:39:10.466636+00, null)"

I have tried passing ....ForeignKey('auth.User') and ...ForeignKey(get_user_model() on Post model (not knowing how it could even be of help to my problem.

I migrated the database from sqlite to PostgreSQL and then checked the Post table on PgAdmin to see if user_id (previously named author_id) was there and it was.

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse

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)
    title = models.CharField(max_length=200)
    text = models.TextField()
    published_date = models.DateTimeField(auto_now=True)

    def __str__(self):
        """String representation"""
        return self.title

    def get_absolute_url(self):
        """Returns the url to access a detailed post"""
        return reverse('post-detail', kwargs={"pk": self.pk})

    class Meta:
        ordering = ['-published_date']
        unique_together = ('user',)

and the views file:

class CreatePostView(CreateView):
    model = Post
    template_name = 'blog/addpost.html'
    fields = ('title', 'text')

Here's the traceback:

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/blog/addpost

Django Version: 2.2.1
Python Version: 3.7.2
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'blog',
 'django.contrib.humanize']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback:

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\backends\utils.py" in _execute
  84.                 return self.cursor.execute(sql, params)

The above exception (null value in column "user_id" violates not-null constraint
DETAIL:  Failing row contains (18, s, s, 2019-05-26 15:39:10.466636+00, null).
) was the direct cause of the following exception:

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\core\handlers\exception.py" in inner
  34.             response = get_response(request)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\core\handlers\base.py" in _get_response
  115.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\core\handlers\base.py" in _get_response
  113.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\views\generic\base.py" in view
  71.             return self.dispatch(request, *args, **kwargs)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\views\generic\base.py" in dispatch
  97.         return handler(request, *args, **kwargs)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\views\generic\edit.py" in post
  172.         return super().post(request, *args, **kwargs)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\views\generic\edit.py" in post
  142.             return self.form_valid(form)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\views\generic\edit.py" in form_valid
  125.         self.object = form.save()

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\forms\models.py" in save
  458.             self.instance.save()

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\models\base.py" in save
  741.                        force_update=force_update, update_fields=update_fields)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\models\base.py" in save_base
  779.                 force_update, using, update_fields,

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\models\base.py" in _save_table
  870.             result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\models\base.py" in _do_insert
  908.                                using=using, raw=raw)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\models\manager.py" in manager_method
  82.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\models\query.py" in _insert
  1186.         return query.get_compiler(using=using).execute_sql(return_id)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql
  1335.                 cursor.execute(sql, params)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\backends\utils.py" in execute
  99.             return super().execute(sql, params)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\backends\utils.py" in execute
  67.         return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\backends\utils.py" in _execute_with_wrappers
  76.         return executor(sql, params, many, context)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\backends\utils.py" in _execute
  84.                 return self.cursor.execute(sql, params)

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\utils.py" in __exit__
  89.                 raise dj_exc_value.with_traceback(traceback) from exc_value

File "C:\Users\ychnk\Desktop\ayancikist_project\venv\lib\site-packages\django\db\backends\utils.py" in _execute
  84.                 return self.cursor.execute(sql, params)

Exception Type: IntegrityError at /blog/addpost
Exception Value: null value in column "user_id" violates not-null constraint
DETAIL:  Failing row contains (18, s, s, 2019-05-26 15:39:10.466636+00, null).

I had created mini-blogs using Django to practice class-based-views and gain more familiarity with coding and django environment. I had followed very similar steps but encountered no such error.

Edit: Here's the addpost.html

{% extends "base.html" %}

{% block content %}
  <form action="{% url 'add-post' %}" method="POST">
    {% csrf_token %}
    <ul>
      <p>{{request.user}}</p>is adding a post:
      <li>
        <label for="title">Post Title</label>
        <input type="text" name="title" value="" required>
        <label for="text">Post text</label>
        <input type="text" name="text" value="">
        <button type="submit" name="button">Publish</button>
        <a href="{% url 'blog-view' %}">
          <button type="submit" name="button">Cancel & Go Back</button>
        </a>
      </li>
    </ul>
  </form>
{% endblock %}

Upvotes: 2

Views: 3052

Answers (1)

Sergey Pugach
Sergey Pugach

Reputation: 5669

It seems that you don't pass user to Post when try to create, but user is required field. You can override form_valid method.

class CreatePostView(CreateView):
    model = Article
    template_name = 'blog/addpost.html'
    fields = ('title', 'text')

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

Upvotes: 2

Related Questions