[Fixed]-Django – null value in column violates not-null constraint in Django Admin

15👍

Looking at your models you shouldn’t have field category_id in any of your tables. Perhaps you changed your models but did not alter tables in the database. Now when you create an entry, Django does not fill fields it doesn’t know about of and this creates an error. You should remove unneeded fields from your tables. Or if it is possible you can drop the whole database and run manage.py syncdb from scratch.

2👍

Just add null=True in all your Fields check https://docs.djangoproject.com/en/3.1/topics/migrations/#postgresql

0👍

I got the same error below with models.ForeignKey():

django.db.utils.IntegrityError: null value in column "categories_id"
of relation "my_app_product" violates not-null constraint

Because I didn’t set null=True when setting blank=True to models.ForeignKey(), then tried to add the blank data --------- on Add page in Django Admin as shown below. *For models.ForeignKey() and models.OneToOneField() in Django, we need to set null=True when setting blank=True:

# "my_app/models.py"

class Category(models.Model):
    name = models.CharField(max_length=20)

class Product(models.Model):
    categories = models.ForeignKey(
        Category, 
        blank=True, # Here 
        on_delete=models.CASCADE
    )
    name = models.CharField(max_length=20)

enter image description here

So, I set null=True with blank=True to models.ForeignKey() as shown below, then the error was solved:

# "my_app/models.py"

class Category(models.Model):
    name = models.CharField(max_length=20)

class Product(models.Model):
    categories = models.ForeignKey(
        Category, 
        blank=True,
        null=True, # Here
        on_delete=models.CASCADE
    )
    name = models.CharField(max_length=20)

Leave a comment