如何自定义Django对IntegerFields的管理验证? [英] How can I customize Django's admin validation of IntegerFields?
问题描述
如果django的内置版本,如何编写自己的自定义整数字段并使用该字段。有关详细信息,请参阅文档。你可能想要覆盖内置的 IntegerField
,那么也许编写自己的FormField 。
我怀疑这是在 ModelForm
上的验证,当您覆盖 clean()
和 clean_fields()
在模型上 - 表单验证将在模型验证之前踢。
尝试这样的事情:
from django.db import models
from django.forms import fields
class IntegerPriceFormField(fields.IntegerField):
def to_python(self,value):
if isinstance(value,basestring):
value = value.replace ,,).replace($,)
return super(IntegerPriceFormField,self).to_python(value)
class IntegerPriceField(models.IntegerField) b $ b def formfield(self,** kwargs):
defaults = {'form_class':IntegerPriceFormField}
defaults.update(kwargs)
return super(IntegerPriceField,self).formfield( **默认值)
然后可以使用Intege您的模型定义为rPriceField而不是IntegerField。
I've got an IntegerField in a Django admin model, and sometimes people type in "2,100" instead of "2100" and Django complains "Enter a whole number." Is it possible to override some method that would allow me to strip out commas, dollar signs, etc, so that the number can be correctly parsed as an integer while being intuitive for users? I've tried clean() and clean_fields(), but they don't seem to be what I want, unless I'm using them incorrectly. Thanks!
How about writing your own custom integer field and using that in place if django's built in version. See the docs for more info. You'll probably want to override the built in IntegerField
, then maybe write your own FormField.
I suspect it's the validation on the ModelForm
that's failing when you override clean()
and clean_fields()
on the model - the form validation will be kicking in before the model validation.
Try something like this:
from django.db import models
from django.forms import fields
class IntegerPriceFormField(fields.IntegerField):
def to_python(self, value):
if isinstance(value, basestring):
value = value.replace(",", "").replace("$", "")
return super(IntegerPriceFormField, self).to_python(value)
class IntegerPriceField(models.IntegerField):
def formfield(self, **kwargs):
defaults = {'form_class': IntegerPriceFormField}
defaults.update(kwargs)
return super(IntegerPriceField, self).formfield(**defaults)
Then you can use IntegerPriceField instead of IntegerField on your model definition.
这篇关于如何自定义Django对IntegerFields的管理验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!