gpt4 book ai didi

django - 在 django admin 中添加新项目时,列 "name"中的空值违反了非空约束

转载 作者:行者123 更新时间:2023-11-29 11:15:59 25 4
gpt4 key购买 nike

我已经向我的管理员添加了一个新模型。这是我的模型.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

还有 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)

当我尝试添加(通过管理员单击添加按钮)时,出现此错误:

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

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

这在以前从未发生过。我知道名称不允许为 Null,但我仍在添加记录。这怎么可能?

最佳答案

此问题的部分原因是未正确使用 CharFieldTextField。您应该几乎永远不要在此字段及其子类上使用null=Truehttps://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.

我强烈建议从您的CharFieldTextField 中删除此参数。

还要确保运行 ./manage.py makemigrations && ./manage.py migrate

关于django - 在 django admin 中添加新项目时,列 "name"中的空值违反了非空约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44783677/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com