Django - null value in column violates not-null constraint in Django Admin

27,242

Solution 1

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.

Solution 2

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

Share:
27,242
Newtt
Author by

Newtt

JavaScript, Django Dev.

Updated on July 27, 2022

Comments

  • Newtt
    Newtt almost 2 years

    I'm facing an Integrity Error in Django admin while trying to add data to the database.

    The traceback is as follows:

      Environment:
    
    
      Request Method: POST
      Request URL: http://127.0.0.1:8000/site/admin/SilverInningsHelpline/classified/add/
    
      Django Version: 1.6.4
      Python Version: 2.7.3
      Installed Applications:
      ('django_admin_bootstrapped.bootstrap3',
       'django_admin_bootstrapped',
       'django.contrib.admin',
       'django.contrib.auth',
       'django.contrib.contenttypes',
       'django.contrib.sessions',
       'django.contrib.messages',
       'django.contrib.staticfiles',
       'SilverInningsHelpline',
       'south')
      Installed Middleware:
      ('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 "/home/siddharth/SilverInnings/venv/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
        114.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
      File "/home/siddharth/SilverInnings/venv/local/lib/python2.7/site-packages/django/contrib/admin/options.py" in wrapper
        432.                 return self.admin_site.admin_view(view)(*args, **kwargs)
      File "/home/siddharth/SilverInnings/venv/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
        99.                     response = view_func(request, *args, **kwargs)
      File "/home/siddharth/SilverInnings/venv/local/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
        52.         response = view_func(request, *args, **kwargs)
      File "/home/siddharth/SilverInnings/venv/local/lib/python2.7/site-packages/django/contrib/admin/sites.py" in inner
        198.             return view(request, *args, **kwargs)
      File "/home/siddharth/SilverInnings/venv/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapper
        29.             return bound_func(*args, **kwargs)
      File "/home/siddharth/SilverInnings/venv/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
        99.                     response = view_func(request, *args, **kwargs)
      File "/home/siddharth/SilverInnings/venv/local/lib/python2.7/site-packages/django/utils/decorators.py" in bound_func
        25.                 return func(self, *args2, **kwargs2)
      File "/home/siddharth/SilverInnings/venv/local/lib/python2.7/site-packages/django/db/transaction.py" in inner
        371.                 return func(*args, **kwargs)
      File "/home/siddharth/SilverInnings/venv/local/lib/python2.7/site-packages/django/contrib/admin/options.py" in add_view
        1131.                 self.save_model(request, new_object, form, False)
      File "/home/siddharth/SilverInnings/venv/local/lib/python2.7/site-packages/django/contrib/admin/options.py" in save_model
        860.         obj.save()
      File "/home/siddharth/SilverInnings/venv/local/lib/python2.7/site-packages/django/db/models/base.py" in save
        545.                        force_update=force_update, update_fields=update_fields)
      File "/home/siddharth/SilverInnings/venv/local/lib/python2.7/site-packages/django/db/models/base.py" in save_base
        573.             updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
      File "/home/siddharth/SilverInnings/venv/local/lib/python2.7/site-packages/django/db/models/base.py" in _save_table
        654.             result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
      File "/home/siddharth/SilverInnings/venv/local/lib/python2.7/site-packages/django/db/models/base.py" in _do_insert
        687.                                using=using, raw=raw)
      File "/home/siddharth/SilverInnings/venv/local/lib/python2.7/site-packages/django/db/models/manager.py" in _insert
        232.         return insert_query(self.model, objs, fields, **kwargs)
      File "/home/siddharth/SilverInnings/venv/local/lib/python2.7/site-packages/django/db/models/query.py" in insert_query
        1511.     return query.get_compiler(using=using).execute_sql(return_id)
      File "/home/siddharth/SilverInnings/venv/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
        903.             cursor.execute(sql, params)
      File "/home/siddharth/SilverInnings/venv/local/lib/python2.7/site-packages/django/db/backends/util.py" in execute
        69.             return super(CursorDebugWrapper, self).execute(sql, params)
      File "/home/siddharth/SilverInnings/venv/local/lib/python2.7/site-packages/django/db/backends/util.py" in execute
        53.                 return self.cursor.execute(sql, params)
      File "/home/siddharth/SilverInnings/venv/local/lib/python2.7/site-packages/django/db/utils.py" in __exit__
        99.                 six.reraise(dj_exc_type, dj_exc_value, traceback)
      File "/home/siddharth/SilverInnings/venv/local/lib/python2.7/site-packages/django/db/backends/util.py" in execute
        53.                 return self.cursor.execute(sql, params)
    
      Exception Type: IntegrityError at /site/admin/SilverInningsHelpline/classified/add/
      Exception Value: null value in column "category_id" violates not-null constraint
    

    My models are as follows:

    class Categories(models.Model):
        id = models.AutoField(primary_key=True)
        type = models.CharField(max_length=300)
    
        def __unicode__(self):
            return self.type
    
    
    class Subcategory(models.Model):
        id = models.AutoField(primary_key=True)
        parent = models.ForeignKey(Categories)
        name = models.CharField(max_length=300)
    
        def __unicode__(self):
            return self.name
    
    
    
    class Classified(models.Model):
        id = models.AutoField(primary_key=True)
        name = models.CharField(max_length=256)
        contact_person = models.CharField(max_length=300)
        email = models.CharField(max_length=100)
        address = models.ForeignKey(Address)
        subcategory = models.ForeignKey(Subcategory)
        phone_number = models.BigIntegerField(max_length=20, default=0)
        image = models.ImageField(blank=True, upload_to='dynamic/img/')
        NO = 'NO'
        YES = 'YES'
        APPROVAL = ((NO, 'no'), (YES, 'yes'))
        active = models.CharField(choices=APPROVAL, default=NO, max_length=3)
        verified = models.CharField(choices=APPROVAL, default=NO, max_length=3)
    
        def __unicode__(self):
            return self.name
    

    The problems arise when I try to make an entry to the Classified table from Admin.

    Tried solution from here:

    IntegrityError: null value in column "city_id " violates not-null constraint as it was the closest to my problem. My tables looked like this after trying the solution on that link:

    class Categories(models.Model):
        id = models.AutoField(primary_key=True)
        type = models.CharField(max_length=300, unique=True, default='All', null=True)
    
        def __unicode__(self):
            return self.type
    
    
    class Subcategory(models.Model):
        id = models.AutoField(primary_key=True)
        parent = models.ForeignKey(Categories, null=True, blank=True, default='All')
        name = models.CharField(max_length=300)
    
        def __unicode__(self):
            return self.name
    
    
    
    class Classified(models.Model):
        id = models.AutoField(primary_key=True)
        name = models.CharField(max_length=256)
        contact_person = models.CharField(max_length=300)
        email = models.CharField(max_length=100)
        address = models.ForeignKey(Address)
        subcategory = models.ForeignKey(Subcategory)
        phone_number = models.BigIntegerField(max_length=20, default=0)
        image = models.ImageField(blank=True, upload_to='dynamic/img/')
        NO = 'NO'
        YES = 'YES'
        APPROVAL = ((NO, 'no'), (YES, 'yes'))
        active = models.CharField(choices=APPROVAL, default=NO, max_length=3)
        verified = models.CharField(choices=APPROVAL, default=NO, max_length=3)
    
        def __unicode__(self):
            return self.name
    

    But this did not solve my problem and now I'm stuck.

  • Newtt
    Newtt almost 10 years
    Would it better if I remove the category primary key field 'id'? Or is it specifically looking for a field called 'category_id'? Also, dropping this database would mean, I'd have to reflect that on Heroku where it's currently deployed and I don't wish to lose any of the live data.
  • Alex Shkop
    Alex Shkop almost 10 years
    I understand. Looks like you have category_id field in your table, but Django does not know about it. So INSERT statement it issues leaves this field blank, but you have NOT NULL constraint. If you have direct access to your database, you should check which table has this column and decide if you need it. If it is not specified in Django then perhaps you are not going to use it.
  • Newtt
    Newtt almost 10 years
    Hmm, I dropped the database and made a new one. manage.py syncdb works well and schemamigration worked too. Hopefully, on push I wont lose data.
  • Mohammad Amin Eskandari
    Mohammad Amin Eskandari about 2 years
    manage.py syncdb command is deprecated in django 1.7. Use the python manage.py migrate instead.