Django模型blank = False不起作用 [英] Django model blank=False does not work?
问题描述
class Person(models.Model):
name = models.CharField(max_length = 50)
请注意,根据 https://docs.djangoproject.com/en/dev/ref/models/fields/
name.blank是默认情况下False这意味着它必须被指定。
但是,我可以成功地创建一个Person对象,如下所示:
Person.objects.create()
注意名称没有指定。发生了什么?
好的,文件的答案是:
请注意,这不同于null。 null纯粹是数据库相关的,而空白是与验证相关的。如果一个字段为空白= True,则表单验证将允许输入一个空值。如果一个字段为空= False,则该字段将被要求。
另一个catch:
请注意,保存模型时,验证器不会自动运行,但如果您使用的是ModelForm,它将在您的表单中包含的任何字段上运行验证器。 / p>
如果您不使用表单,您有责任在保存前调用干净的方法。
blank
仅适用于在admin,django表单等中的表单字段验证。
null
另一方面是数据库级可空的列。
至于为什么空白的结果是默认''
,我真的只是接受它是这是它的工作方式,但这里是似乎在$ code> django.db.models field
def get_default(self):
返回该字段的默认值。
如果self.has_default():
如果可调用(self.default):
return self.default()
return force_unicode(self.default ,strings_only = True)
if(not self.empty_strings_allowed or(self.null and
not connection.features.interprets_empty_strings_as_nulls)):
return None
return
#^这个
I have the following model in Django 1.5:
class Person(models.Model):
name = models.CharField(max_length=50)
Note that according to https://docs.djangoproject.com/en/dev/ref/models/fields/ name.blank is by default False which means it must be specified.
However, I could successfully create a Person object as follows:
Person.objects.create()
Notice the name is not specified. What is going on?
Ok, the answer from the docs is :
Note that this is different than null. null is purely database-related, whereas blank is validation-related. If a field has blank=True, form validation will allow entry of an empty value. If a field has blank=False, the field will be required.
Another catch:
Note that validators will not be run automatically when you save a model, but if you are using a ModelForm, it will run your validators on any fields that are included in your form.
It's your responsibility to call the clean methods before saving if you're not using a form.
blank
only applies to form field validation as in the admin, django forms, etc.
null
on the other hand is a database level nullable column.
As for why blank results in a default ''
, I had really just accepted it as "that's the way it works" but here's where it appears to be in django.db.models.Field
def get_default(self):
"""
Returns the default value for this field.
"""
if self.has_default():
if callable(self.default):
return self.default()
return force_unicode(self.default, strings_only=True)
if (not self.empty_strings_allowed or (self.null and
not connection.features.interprets_empty_strings_as_nulls)):
return None
return ""
# ^ this
这篇关于Django模型blank = False不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!