2016-06-10 2 views
0

주위 루프 내가 그렇게 보이는 세 가지 형태가 오류 '범위를 벗어난 팝 지수'장고 - 다수의 formset

PeopleForm의 수량 값 rooms RoomsForm의 필드와 ChildrenAgeForm의 양에 따라 달라집니다
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) 

에 따라 달라집니다 각 children 필드의 값은 PeopleForm입니다. 그래서 PeopleFormChildrenAgeForm에 대한 formsets을 만들고 js를 사용하여 곱합니다. 나는 views.py 파일에서 루프 스크립트 작성이에 따르면

'<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>' 

:

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) 

을하지만 난 마지막으로 내가 rooms의 값이, 예를의, 3 경우 다음과 같습니다 문자열을 작성해야 오류 pop index out of range이 있습니다. 올바른 방법으로 스크립트를 편집 할 수있게 도와주세요. 당신은 목록에서 요소를 제거하고 pop를 사용하여

답변

1

:

>>> 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의 요소에 액세스 : 때문에 초기화, childrenage_str = '' 다음 childrenage_lst = childrenage_str, 그것은 childrenage_lst 모양의 말했다

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

pop 메서드가없는 문자열이므로 게시 한 코드에 누락 된 내용이 있으므로 TraceBack을 얻으려고합니다.

+0

답변을 주셔서 감사합니다. 내 게시물에서 실수로'childrenage_str = []','childrenage_str'은 string이 아니며 –