Django - 如何设置blank = False,required = False [英] Django - how to set blank = False, required = False
问题描述
我有一个这样的模型:
class Message(models.Model):
msg = models.CharField(max_length = 150)
我有一个表单插入字段。实际上django允许空的空间,例如,如果我在现场插入一个空间,它的作用。但现在我想解决这个问题:该字段不是必需的,但是如果用户插入一个空格,验证将失败。
and I have a form for insert the field. Actually django allows empty spaces, for examples if I inset in the field one space it works. But now I want to fix this: the field is not required, but if a user insert a spaces, the validation should fail.
我添加了:
class Message(models.Model):
msg = models.CharField(max_length = 150, blank = False)
但它不工作。
什么是错误?
but it doesn't work. What's the mistake?
推荐答案
空格不被认为是空白。 空白具体是指不输入(即空字符串''
)。如果值仅包含空格,则需要使用模型字段验证器引发异常。有关详细信息,请参见文档。
Whitespace is not considered to be blank. blank specifically refers to no input (i.e. an empty string ''
). You will need to use a model field validator that raises an exception if the value only consists of spaces. See the documentation for details.
示例:
def validate_not_spaces(value):
if value.strip() == '':
raise ValidationError(u"You must provide more than just whitespace.")
class Message(models.Model):
msg = models.CharField(max_length=150, blank=False,
validators=[validate_not_spaces])
这篇关于Django - 如何设置blank = False,required = False的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!