如何自定义Django对IntegerFields的管理验证? [英] How can I customize Django's admin validation of IntegerFields?

查看:244
本文介绍了如何自定义Django对IntegerFields的管理验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Django管理模式中有一个IntegerField,有时候人们会输入2,100而不是2100,Django抱怨输入一个数字。是否可以覆盖一些可以让我删除逗号,美元符号等的方法,以便数字可以正确地解析为一个整数,同时直观的用户?我已经尝试了clean()和clean_fields(),但它们似乎不是我想要的,除非我使用不正确。谢谢!

解决方案

如果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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆