The null value in the "name" column violates the null-null constraint when adding a new element in django admin

I added a new model for my admin. These are 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 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 the add button through 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 that the name cannot be Null , but I am adding an entry anyway. How is this possible?

+5
source share
2 answers

There is a short answer here.
If you specify the field as a nonzero field, django will ask you to either specify a default value in the code itself, or ask you to provide a default value when performing the migration. A better approach would be to provide some normal default value in your models.py file. After that, do python manage.py makemigrations and python manage.py migrate . You must be fine.

+2
source

This problem is partly due to the misuse of CharField and TextField . You should almost never use null=True in these fields and their subclasses. https://docs.djangoproject.com/en/1.11/ref/models/fields/#django.db.models.Field.null

Avoid using null for string fields like CharField and TextField. If the string field has null = True, it means that it has two possible values ​​for "no data": NULL and an empty string. In most cases, its redundancy has two possible meanings for “no data”; The Django convention should use an empty string, not NULL. The only exception is when CharField has both unique = True and blank = True. In this situation, null = True is required to avoid unique constraint violations when storing multiple objects with empty values.

I would strongly suggest removing this option from your CharField and TextField s.

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

+7
source

Source: https://habr.com/ru/post/1269257/


All Articles