3 回答

TA贡献1856条经验 获得超17个赞
问题不在于您的字段定义。它与手动创建模型实例时的验证有关。您需要自己执行完整的验证,因为您没有使用 ModelForm。
使用这个例子:
from django.core.exceptions import ValidationError
thing = Thing(thing_id='123')
try:
thing.full_clean()
thing.save()
except ValidationError:
# Handle validation issues.
阅读文档中的这一部分:https : //docs.djangoproject.com/en/2.1/ref/models/instances/#validating-objects
从那里引用:
请注意,当您调用模型的 save() 方法时,不会自动调用 full_clean()。当您想为自己手动创建的模型运行一步模型验证时,您需要手动调用它

TA贡献1966条经验 获得超4个赞
默认情况下null,对于每个模型字段black都是 False链接。不需要添加那些。
from django.db import models
class Thing(models.Model):
document = models.FileField()
thing_id = models.CharField()

TA贡献1804条经验 获得超8个赞
您可以直接在模型覆盖save()方法中添加验证:
class Thing(models.Model):
document = models.FileField(null=False, blank=False, default=None)
thing_id = models.CharField(max_length=200)
def save(self, *args, **kwargs):
self.full_clean()
super().save(*args, **kwargs)
添加回答
举报