Django 中的 DecimalField 验证 [英] DecimalField Validation in Django

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

问题描述

我正在尝试验证 Django 中的 DecimalField

I'm trying to validate a DecimalField in Django

在 shell 中尝试:

Trying in shell:

>> from django.forms import DecimalField
>> from django.core.validators import MaxValueValidator
>> f = DecimalField(max_digits=2, decimal_places=1, validators=[MaxValueValidator(10)])
>> f.validate(11) # after this I should get an error
>>

但它没有显示验证错误.它应该抛出一个错误,因为 11 大于 10,对吗?

But it does not show validation errors. It should throw an error because 11 is greater that 10, right?

我做错了什么?

推荐答案

您是字段声明中的 1 个问题.如果 max_digits = 2 和 decimal_places = 1,则在没有验证器干预的情况下,最大值为 9.9.

You are 1 problem in field declaration. if max_digits = 2 and decimal_places = 1, your max is 9.9 without the intervention of validators.

max_digits = 3 和 max = 10.0 的验证器

max_digits = 3 and validators for max = 10.0

使用clean()函数:

>> from django.forms import DecimalField
>> from django.core.validators import MaxValueValidator
>> f = DecimalField(max_digits=3, decimal_places=1, validators=[MaxValueValidator(10)])
>> f.clean(11.2)

https://docs.djangoproject.com/en/1.10/ref/forms/validation/

这篇关于Django 中的 DecimalField 验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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