python - Django - 内联表单集验证
问题描述
我正在尝试验证我的内联表单集成本值,以确保它加起来为 100。表单集返回 5 次,因此应该添加 foreach 值,直到达到 100。如果它或多或少显示错误并且不允许用户点击创建按钮。我正在尝试验证所有组合的表单,而不是每个表单值。
模型.py
class EstimatedBudgetForm(forms.ModelForm):
def clean(self):
# get forms that actually have valid data
count = 0
for percentage in self.cost:
try:
if percentage.cleaned_data:
count += percentage
except AttributeError:
# annoyingly, if a subform is invalid Django explicity raises
# an AttributeError for cleaned_data
pass
if count != 100:
raise forms.ValidationError('Percentage must equal 100%')
视图.py
EstimatedBudgetChildFormset = inlineformset_factory(
Project, EstimatedBudget, fields=('project', 'item', 'cost', 'time'), can_delete=False, form=EstimatedBudgetForm, extra=5, widgets={'item': forms.Select(attrs={'disabled': True})},
)
解决方案
要对表单集执行验证,应该覆盖clean
表单集(而不是表单)的方法。对于内联表单集,您需要继承BaseInlineFormSet
并使用它(有关更多信息,请参阅在 ModelFormSet [Django docs] 上覆盖 clean()):
from django.forms import BaseInlineFormSet
class MyInlineFormset(BaseInlineFormSet):
def clean(self):
super().clean()
count = 0
for form in self.forms:
if not form.errors: # No need for a try-except, just check if the form doesn't have errors
count += form.cleaned_data['cost']
if count != 100: # This condition might not work if you are dealing with floating point numbers
raise forms.ValidationError('Percentage must equal 100%')
接下来在制作表单集时,指定formset
kwarg 而不是form
:
EstimatedBudgetChildFormset = inlineformset_factory(
Project, EstimatedBudget, fields=('project', 'item', 'cost', 'time'), can_delete=False, formset=MyInlineFormset, extra=5, widgets={'item': forms.Select(attrs={'disabled': True})},
)
推荐阅读
- javascript - 从数组中提取最后 n 个元素而不干扰原始数组
- javascript - 更改 Redux 中的存储
- java - Android中是否有任何有效的方法来缩小文件中的大图像并将其保存到新文件而不会出现OOM异常
- java - 如何与批处理进行通信?
- spark-java - Spark 可以支持每条路由多少个并发请求?
- php - Symfony 中的简单查询返回 null
- header - Zip 是否使用字典进行压缩?是否可以提取该字典并将其转储到文本文件中?
- youtube-api - Youtube API - 允许订阅用户,但次日取走
- java - 在我的 txt 文件的每一行添加一个空格
- regex - 条件正则表达式模板