Django中ModelField的自定义验证 [英] Custom validation of a ModelField in Django
问题描述
我的模型看起来像这样:
my model looks like this:
class MyModel(models.Model):
field1 = models.FloatField(default=0)
field2 = models.FloatField(default=0)
它的行为如何:
>>> m = MyModel()
>>> m.full_clean()
>>> m = MyModel(field1=8.9)
>>> m.full_clean()
>>> m = MyModel(field1='')
>>> m.full_clean()
ValidationError: {'field1': [u'This value must be a float.'], ...
我希望它接受空白字符串并使用0.我也希望它接受诸如5:56之类的值,并使用5.93333。 (我已经有一个可以做到这一点的功能)
I want it to accept blank strings and have it use 0. I also want it to accept values such as "5:56" and have it use "5.93333". (I already have a function that can do this)
目前我有一个使用自定义表单字段(它是丑陋的罪恶),但我想移动它全部使用模型验证。
Currently I have this working with a custom form field (and it's ugly as sin), but I want to move it all to use model validation. Whats the best way to go about this?
推荐答案
制作一个 clean_field1
在您的表单功能,并在那里验证。如果不正确,则抛出验证错误,并重新格式化并返回正确值。示例:
Make a clean_field1
function in your form and verify it in there. Throw a validation error if it's improper, and reformat and return the "proper" value if it is. Example:
http://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-a-specific-field-attribute
更新:
问题澄清:用户想要一个模型字段来执行此操作。
Question clarified: user wants a Model Field that does this.
覆盖 FloatField
和 get_prep_value
和 to_python
例程内部:
class MagicalFloatField(FloatField):
def to_python( self, value_from_db ):
...
return what_should_go_into_model_field_value
def get_prep_value( self, value_from_field ):
...
return what_should_go_into_db
所以你可以在那里做5:26 - 5.26。然后在您的模型中使用您的字段:
So you can do the "5:26" <--> "5.26" there. Then use your field in your model:
class MagicalModel(Model):
foo = MagicalFloatField()
参考:
http://docs.djangoproject.com/en/dev/ howto / custom-model-fields /#django.db.models.to_python
此外,还有一个例子,它期待什么以及如何提高验证错误,看看你是什么子类 - 在 site-packages / django / db / models / fields / __ init __。py >中查找
FloatField
code>
Also, for an example of what it expects and how to raise validation errors, look at what you're subclassing -- look up FloatField
in site-packages/django/db/models/fields/__init__.py
这篇关于Django中ModelField的自定义验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!