Django setset中的帮助循环仅返回form.py中的最后一个索引

时间:2019-03-25 10:03:34

标签: django django-models django-forms django-views

试图循环forms.py内的formset表单,但它仅返回formset的最后一个索引,而不是所有索引。 forms.py:

class MyModelFormSet(BaseModelFormSet):
def clean(self):
    super(MyModelFormSet, self).clean()

    totalforms = self.total_form_count() #to get number of forms in formset

    for form in self.forms:
        for n in range(totalforms):
            d = self[n].cleaned_data['debit'] # if i use  manullay self[0], self[1] it works
        if d == 100:
            raise forms.ValidationError('debit is 100!')
        return d

1 个答案:

答案 0 :(得分:0)

最终通过NVS评论解决 这是更新的代码: 首先需要设置一个列表,然后附加到该列表

class MyModelFormSet(BaseModelFormSet):
def clean(self):
    super(MyModelFormSet, self).clean()

    totalforms = self.total_form_count() #to get number of forms in formset
    ds = []
    for form in self.forms:
        for n in range(totalforms):
            d = self[n].cleaned_data['debit']
            ds.append(d)
        if 100 in ds:
            raise forms.ValidationError('debit is 100!')
        return d