Django - 循环多个formset时'pop index超出范围'错误

时间:2016-06-10 13:09:51

标签: python django

我有三种形式:

class RoomsForm(forms.Form):
  rooms = forms.IntegerField(min_value=1)
class PeopleForm(forms.Form):
  adult = forms.IntegerField(min_value=1)
  children = forms.IntegerField(required=False)
class ChildrenAgeForm(forms.Form):
  children_age = forms.IntegerField(max_value=10, required=False)

PeopleForm的数量取决于rooms的值RoomsForm字段和ChildrenAgeForm的数量取决于每个children的值PeopleForm字段。因此,我为PeopleFormChildrenAgeForm创建了表单集,并使用js将其相乘。最后,如果rooms的值为3,我需要创建看起来像这样的字符串:

'<Room Adult=2 Children=2>
  <ChildAge>2</ChildAge>
  <ChildAge>1</ChildAge>
</Room>
<Room Adult=1 Children=0>
</Room>
<Room Adult=1 Children=1>
  <ChildAge>3</ChildAge>
</Room>'

根据这个我在views.py文件中创建循环脚本:

PeopleFormSet = formset_factory(PeopleForm, extra = 1, max_num = 15)
ChildrenAgeFormSet = formset_factory(ChildrenAgeForm, extra = 1, max_num = 20)
rooms_form = RoomsForm(request.POST, prefix='rooms_form')
people_formset = PeopleFormSet(request.POST, prefix='people')
childrenage_formset = ChildrenAgeFormSet(request.POST, prefix='childrenage')
if room_form.is_valid() and people_formset.is_valid() and childrenage_formset.is_valid():
  people = ''
  childrenage_str = []
  for i in range(0, childrenage_formset.total_form_count()):
    childrenage_form = childrenage_formset.forms[i]
    childrenage = str(childrenage_form.cleaned_data['children_age'])
    childrenage_str += childrenage
  for n in range(0, people_formset.total_form_count()):
     childrenage_lst = childrenage_str
     people_form = people_formset.forms[n]
     adults = str(people_form.cleaned_data['adult'])
     children = people_form.cleaned_data['children']
     for i in range(0, children):
       childage_str = ''
       childage = childrenage_lst.pop(i)
       childage_str += '<ChildAge>%s</ChildrenAge>' % childage
       people += '<Room Adults="%s">%s</Room>' % (adults, childage_str)

但是我收到了错误pop index out of range。希望你能帮助我以正确的方式编辑我的脚本。

1 个答案:

答案 0 :(得分:1)

使用pop您从列表中删除元素:

>>> mylist = [0,1,2,3,4,5,6,7,8,9]
>>> for i in range(0, len(mylist)): 
...     print(mylist)
...     print(mylist.pop(i))
...
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
0
[1, 2, 3, 4, 5, 6, 7, 8, 9]
2
[1, 3, 4, 5, 6, 7, 8, 9]
4
[1, 3, 5, 6, 7, 8, 9]
6
[1, 3, 5, 7, 8, 9]
8
[1, 3, 5, 7, 9]
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
IndexError: pop index out of range

所以children,你使用的长度是恒定的,但childrenage_lst不断变得越来越短。如果您确信两者的长度始终相同,那么只需使用childrenage_lst访问[]中的元素:

for i in range(0, children):
    print(childrenage_lst[i])

那就是说,由于它的初始化childrenage_str = ''然后是childrenage_lst = childrenage_str,看起来childrenage_lst是一个字符串,它没有pop方法,所以我认为您发布的代码中缺少一些东西,以获得您正在获取的TraceBack。