gpt4 book ai didi

python - Django - 内联表单集验证

转载 作者:行者123 更新时间:2023-12-05 02:00:23 25 4
gpt4 key购买 nike

我正在尝试验证我的内联表单集成本值,以确保它加起来等于 100。表单集返回 5 次,因此应该为每个值添加值,直到达到 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%')

Views.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 并使用它(有关更多信息,请参阅 Overriding clean() on a ModelFormSet [Django docs] ):

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})},
)

关于python - Django - 内联表单集验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67399926/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com