[英]Django CharField accepting empty values when it shouldn't
I have the following model: 我有以下模型:
class ClientDebt(models.Model):
client_id = models.CharField(max_length=255)
...
I was expecting this model to prevent records without a client_id, but I quite don't understand why I can create a ClientDebt without a client_id using a django shell ( python manage.py shell_plus
). 我期望这种模型可以阻止没有client_id的记录,但是我完全不明白为什么我可以使用Django shell(
python manage.py shell_plus
)在没有client_id的情况下创建ClientDebt。
Changing it to CharField(max_length=255, null=False, blank=False)
and trying to create+execute new migrations also didn't work, as Django did not detected any changes. 将其更改为
CharField(max_length=255, null=False, blank=False)
并尝试创建并执行新迁移也没有用,因为Django未检测到任何更改。 There is no default value from what I could see in previous migrations, but it seems to be recording "" (empty string) in the field. 我在以前的迁移中没有看到默认值,但似乎在字段中记录了“”(空字符串)。
Can anybody tell me what is going on? 谁能告诉我发生了什么事? Why is my model accepting null/blank values?
为什么我的模型接受空值/空白值? Can this be a bug in Django?
这可能是Django中的错误吗? I'm using Django version 2.2.1
我正在使用Django 2.2.1版
Have a look at this answer : 看看这个答案 :
class ClientDebt(models.Model):
client_id = models.CharField(max_length=255, blank=False, default=None)
...
blank
will prevent an empty string to be provided in your model blank
将阻止在模型中提供空字符串 default=None
will set name to None when using something like group = Group()
, thus raising an exception when calling save
default=None
在使用group = Group()
类的名称时会将name设置为None,从而在调用save
时引发异常 Alternatively, you may want to have a look at MinLengthValidator . 另外,您可能想看看MinLengthValidator 。
您可以在字段中设置default = ''
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.