Django模型blank = False不起作用

编程入门 行业动态 更新时间:2024-10-14 20:23:55
本文介绍了Django模型blank = False不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我在Django 1.5中有以下模型:

class Person(models.Model): name = models.CharField(max_length = 50)

请注意,根据 docs.djangoproject/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 docs.djangoproject/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不起作用

本文发布于:2023-11-24 01:14:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1623430.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不起作用   模型   Django   False   blank

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!