1

我在 Django 管理模型中有一个 IntegerField,有时人们输入“2,100”而不是“2100”,Django 抱怨“输入一个整数”。是否可以重写一些允许我去掉逗号、美元符号等的方法,以便可以将数字正确解析为整数,同时对用户来说是直观的?我尝试过 clean() 和 clean_fields(),但它们似乎不是我想要的,除非我使用不正确。谢谢!

4

1 回答 1

2

如果 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):
    def formfield(self, **kwargs):
        defaults = {'form_class': IntegerPriceFormField}
        defaults.update(kwargs)
        return super(IntegerPriceField, self).formfield(**defaults)

然后,您可以在模型定义中使用 IntegerPriceField 而不是 IntegerField。

于 2013-03-08T22:25:31.997 回答