14

I have added a new model to my admin. This is my models.py:

class EngineeringToolAttributeType(models.Model):
    name = models.CharField(max_length=50)
    description = models.CharField(max_length=255, blank=True, null=True)
    api_url = models.CharField(max_length=255, blank=True, null=True)
    api_field = models.CharField(max_length=50, blank=True, null=True)
    active = models.BooleanField(default=True)

    def __str__(self):
        return self.name

And the admin.py:

from extras.models import EngineeringToolAttributeType
from django.contrib import admin

class EngineeringToolAttributeTypeAdmin(admin.ModelAdmin):
    fields = ['name', 'description', 'api_url', 'api_field', 'active']
    list_display = ('name', 'description', 'api_url', 'api_field', 'active')

admin.site.register(EngineeringToolAttributeType, EngineeringToolAttributeTypeAdmin)

When I try to add (click on add button via the admin), I get this error:

Internal Server Error: /website/admin/extras/engineeringtoolattributetype/add/

IntegrityError at /admin/extras/engineeringtoolattributetype/add/
null value in column "name" violates not-null constraint

This has never happened before. I know name is not allowed to be Null, but I'm still adding a record. How is that possible?

Bono
  • 4,757
  • 6
  • 48
  • 77
Ruben
  • 1,065
  • 5
  • 18
  • 44

2 Answers2

13

This issue is partially result of not using CharField and TextField properly. You should almost never use null=True on this fields and their subclasses. https://docs.djangoproject.com/en/1.11/ref/models/fields/#django.db.models.Field.null

Avoid using null on string-based fields such as CharField and TextField. If a string-based field has null=True, that means it has two possible values for “no data”: NULL, and the empty string. In most cases, it’s redundant to have two possible values for “no data;” the Django convention is to use the empty string, not NULL. One exception is when a CharField has both unique=True and blank=True set. In this situation, null=True is required to avoid unique constraint violations when saving multiple objects with blank values.

I would highly suggest removing this param from yourCharFields and TextFields.

Also just to be sure run ./manage.py makemigrations && ./manage.py migrate.

Sardorbek Imomaliev
  • 14,861
  • 2
  • 51
  • 63
  • 3
    in fact, name is NOT NULL (you can see it in my model), which is ok, but I get the "null" problem anyways – Ruben Jul 11 '17 at 09:12
3

This has a short answer here.
If you specify a field as not null field django will ask you to either provide a default value in code itself or it will ask you to provide a default value when you run migrations. A better approach would be to provide some sane default in your models.py itself. After that run python manage.py makemigrations and python manage.py migrate. You should be fine.

rmad17
  • 164
  • 7