Django Form中如何根据一个FloatField值设置另一FloatField的数值限制
Django Form跨字段值比较校验方法
你可以通过重写Form类的clean()方法实现跨字段的规则校验,具体实现方式如下:
- 重写Form类的
clean方法,先调用父类方法获取所有字段经过基础校验后的清洗数据 - 单独取出
demand和production_rate两个字段的取值做比较 - 若
production_rate小于等于demand,直接抛出校验错误即可 - 最后返回所有清洗后的数据
完整代码示例:
from django import forms from django.core.exceptions import ValidationError class YourCustomForm(forms.Form): demand = forms.FloatField(label='Demand:', min_value=0) production_rate = forms.FloatField(label='Production rate:', min_value=0) def clean(self): cleaned_data = super().clean() # 先确保两个字段都通过了基础非空、最小值校验 demand_val = cleaned_data.get('demand') prod_rate_val = cleaned_data.get('production_rate') if demand_val is not None and prod_rate_val is not None: if prod_rate_val <= demand_val: raise ValidationError('Production rate的取值必须大于Demand的取值') return cleaned_data
如果需要把错误提示绑定到
production_rate字段下方,而非作为表单全局错误展示,可以把抛出异常的代码替换为:self.add_error('production_rate', 'Production rate的取值必须大于Demand的取值')
内容的提问来源于stack exchange,提问作者Andrey Vinajera
相关产品推荐
相关产品推荐

