Django如何编写PositiveDecimalField

Ear*_*der 2 django django-models django-validation

我想写 PositiveDecimalField。

这是我的代码:

from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _

from django.db.models import DecimalField
from decimal import *

def validate_positive_decimal(value):
    try:
        decimal_value = Decimal(value)

        if decimal_value < 0:
            raise ValidationError(_('{val} should be a positive decimal number'.format(val = decimal_value)), code='negative decimal')

    except (ValueError, TypeError):
        raise ValidationError(_('Enter a valid decimal or integer value'), code='invalid decimal')


class PositiveDecimalField(DecimalField):
    default_validators = [validate_positive_decimal]

    def __init__(self, *args, **kwargs):

        super(DecimalField, self).__init__(*args, **kwargs)

    def validators(self):
        return super(PositiveDecimalField, self).validators + [validate_positive_decimal]
Run Code Online (Sandbox Code Playgroud)

然后,在我的 models.py 中

class Service(models.Model):
    service_rate = PositiveDecimalField(max_digits = 6, decimal_places=2, blank=True) # e.g. 125.25 for water (demo phase), -125.25 should not be accepted
Run Code Online (Sandbox Code Playgroud)

我得到的错误是这样的:

super(DecimalField, self).__init__(*args, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'max_digits'
Run Code Online (Sandbox Code Playgroud)

我在文档中查看了 Django DecimalField 的源代码。我还尝试将验证器 validate_positive_decimal 传递给 DecimalField,但它不会对其进行验证。

我需要在这里做什么?

Rav*_*jha 5

我通常将这些字段定义为:

from django.core.validators import MinValueValidator

pos_float_field = models.FloatField(validators=[MinValueValidator(0.0)])
Run Code Online (Sandbox Code Playgroud)

这样更干净。

文档:MinValueValidator