自定义 Django 字段的验证
有一个 Django 字段类型用于存储 MyType
的值。
from django.core.exceptions import ValidationError
from django.db import models
class MyTypeField(models.Field):
__metaclass__ = models.SubfieldBase
def db_type(self, connection):
return "text"
def to_python(self, value):
if isinstance(value, basestring):
try:
value = MyType.deserialize(value)
except ParseError, e:
raise ValidationError("Invalid format: "+str(e))
assert isinstance(value, MyType)
return value
def get_prep_value(self, value):
if not isinstance(value, MyType):
raise ValidationError("Not MyType")
return value.serialize()
我正在尝试在模型的管理页面上使用这种类型的字段。如果用户在字段中输入有效值,一切都会正常工作。但是,如果输入的值无效,则不会捕获 ValidationError
(您会收到错误 500,或者如果启用了调试,则会出现堆栈跟踪)
相反,我想在表单附近看到一条消息“无效格式”字段(就像您输入无效的日期或数字一样)。如何修改字段类以在正确的位置获取验证错误。
There is a Django field type for storing values of MyType
.
from django.core.exceptions import ValidationError
from django.db import models
class MyTypeField(models.Field):
__metaclass__ = models.SubfieldBase
def db_type(self, connection):
return "text"
def to_python(self, value):
if isinstance(value, basestring):
try:
value = MyType.deserialize(value)
except ParseError, e:
raise ValidationError("Invalid format: "+str(e))
assert isinstance(value, MyType)
return value
def get_prep_value(self, value):
if not isinstance(value, MyType):
raise ValidationError("Not MyType")
return value.serialize()
I am trying to use fields of this type on an admin page of a model. Everything works nice if a user enters a valid value in the field. But if the entered value is invalid, the ValidationError
is not caught (you get error 500, or a stack trace if debug is enabled)
Instead I want to see the form with a message "Invalid format" near the field (just like if you enter an invalid date or number). How to modify the field class to get validation errors in a correct place.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
引用自 http://docs。 djangoproject.com/en/1.2/howto/custom-model-fields/#modelforms-and-custom-fields
因此,此时将永远不会捕获 ValidationError。从数据库填充模型的新实例时也会调用 to_python ,该数据库位于表单验证上下文之外。
因此,您必须将验证移至表单字段中。
Quoting from http://docs.djangoproject.com/en/1.2/howto/custom-model-fields/#modelforms-and-custom-fields
So a ValidationError will never be caught at this point.
to_python
is also called when populating a new instance of your model from the database, which is outside the form validation context.So you have to move your validation into a formfield.
您需要在字段类中创建一个 clean(self, value, model_instance) 方法并在那里进行验证/引发错误。
You need to create a
clean(self, value, model_instance)
method in your field class and do the validation/raise the error there.