How to Solve Error Message psycopg2.errors.NotNullViolation: null value in column “id” violates not-null constraint in Python Django-web based Application

Posted on

Introduction

An error appears upon executing a script in python command shell. The script is a part of script where it is mainly a Django framework script. There is a scenario to test whether a form exist in Django web-based applicatoin is working or not. One way to test if it is working or not is by executing it in the python command shell. The following is the complete output of the script execution where in the end it trigger the error message :

user@hostname:~/python/django/project$ python
Python 3.6.8 (default, Jan 14 2019, 11:02:34) 
[GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os;
>>> os.environ['DJANGO_SETTINGS_MODULE'] = 'posting.settings';
>>> import django;
>>> django.setup();
>>> from app.models import Employee;
>>> from app.forms import EmployeeForm;
>>> form = EmployeeForm({'name':"Mike"});
>>> form.save();
Traceback (most recent call last):
  File "/home/user/python/django/env/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
psycopg2.errors.NotNullViolation: null value in column "employee_id" violates not-null constraint
DETAIL:  Failing row contains (null, Mike).

The error above is ‘Failing row contains (null, Mike)’. This error is informing that the save method script execution is failing because of the not-null constraint violation. That information available in the line ‘psycopg2.errors.NotNullViolation: null value in column “user_id” violates not-null constraint’.

There are several snippet code in the above error message occurrence. Before going further, below is the directory structure of the Django web-based application describing the condition and the environment where the above error occurs :

user@hostname:~/python/django$ tree -L 3
.
├── env
└── project
    ├── db.sqlite3
    ├── manage.py
    ├── app
    │   ├── admin.py
    │   ├── apps.py
    │   ├── forms.py
    │   ├── __init__.py
    │   ├── migrations
    │   ├── models.py
    │   ├── __pycache__
    │   ├── templates
    │   ├── tests.py
    │   ├── urls.py
    │   └── views.py
    ├── project
    │   ├── __init__.py
    │   ├── __pycache__
    │   ├── settings.py
    │   ├── urls.py
    │   └── wsgi.py
    └── static
        ├── css
        ├── img
        └── js
20 directories, 29 files
(env) user@hostname:~/python/django$ 

There are two important files in the context of this article. It exist in a folder with the name of ‘app’. It is part of the content available in a file with the name of ‘models’. The first one is a file containing script for defining a model with the name of ‘User’. The following is the snippet code of the model :

class Employee(models.Model):
        employee_id = models.BigIntegerField(primary_key=True)
        name = models.CharField(max_length=200)
        def __str__(self):
                return self.name

The second one is a file containing script for defining a form with the name of ‘EmployeeForm’. The following is the snippet code of the form :

class EmployeeForm(forms.ModelForm):
        class Meta:
                model = Employee
                exclude = ('employee_id',)
                fields = ('name',)

Problem Solving

In order to solve the above problem, the following solution is actually works. Just modify the class with the name of ‘Employee’ into the following form. Fortunately, it only takes only one line modification. Below is the modification of that line :

employee_id = models.BigIntegerField(primary_key=True)

Just change the above line as follows :

employee_id = models.AutoField(primary_key=True)

Don’t forget to run the migration process again. Execute the following command to perform the migration process for implementing the change above :

(env) user@hostname:~/python/django/project$ python manage.py makemigrations app
Migrations for 'app':
  app/migrations/0002_auto_20190825_0814.py
    - Alter field employee_id on app
(env) user@hostname:~/python/django/project$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, app, contenttypes, sessions
Running migrations:
  Applying app.0002_auto_20190825_0814... OK
(env) user@hostname:~/python/django-posting/posting$

After successfully performing the migration, don’t forget to try to execute the previous process. The following is the process re-execution :

(env) user@hostname:~/python/django/project$ python manage.py shell
Python 3.6.8 (default, Jan 14 2019, 11:02:34) 
[GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> import os;
>>> os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings';
>>> import django;
>>> django.setup();
>>> from app.forms import EmployeeForm;
>>> f = EmployeeForm({'name':'Mike'});
>>> f.save();
>>> 

As it shows above, the solution above overcomes the problem and it solve to get rid of the error message.

Leave a Reply