的下面的Django視圖不斷引發錯誤異常值:列表分配索引超出範圍
異常值:全局名稱「圖像」沒有定義
views.py
PATH_ONE_IMAGES = ['P1D1.jpg', 'P2D2.jpg', 'P3D3.jpg', 'P4D4.jpg', 'P5D5.jpg', 'P6D6.jpg', 'P7D7.jpg', 'P8D8.jpg', 'P9D9.jpg']
class SurveyWizardOne(SessionWizardView):
def get_context_data(self, form, **kwargs):
context = super(SurveyWizardOne, self).get_context_data(form, **kwargs)
if self.steps.current in ['5','6','7','8','9','10','11','12','13','14','15','16']:
print '\nThe available list of Path_One images is', PATH_ONE_IMAGES
images = []
step = int(self.steps.current)
if step in (5, 6, 7):
images[step - 5] = image = random.choice(PATH_ONE_IMAGES)
PATH_ONE_IMAGES.remove(image)
context['display_image'] = image
elif step == 8:
context['first_image'] = images[0]
context['second_image'] = images[1]
context['third_image'] = images[2]
elif step in (9, 10, 11):
images[3 + step - 9] = image = random.choice(PATH_ONE_IMAGES)
PATH_ONE_IMAGES.remove(image)
context['display_image'] = image
elif step == 12:
context['fourth_image'] = images[3]
context['fifth_image'] = images[4]
context['sixth_image'] = images[5]
elif step in (13, 14, 15):
images[6 + step - 13] = image = random.choice(PATH_ONE_IMAGES)
PATH_ONE_IMAGES.remove(image)
context['display_image'] = image
else:# self.steps.current == '16':
context['fourth_image'] = images[6]
context['fifth_image'] = images[7]
context['sixth_image'] = images[8]
steps = ['5','6','7','9','10','11','13','14','15']
context.update({'steps': steps})
return context
當我使用
來定義'圖像'時 ....
if self.steps.current in ['5','6','7','8','9','10','11','12','13','14','15','16']:
images = []
step = int(self.steps.current)
if step in (5, 6, 7):
....
我得到
異常值:列表分配索引超出範圍
如果我值添加到它
images = [0,1,2,3,4]
他們變得硬編碼並沒有考慮的價值的PATH_ONE_IMAGES
任何人都可以看到我在這裏做錯了什麼?如何定義圖像數組,使其列表分配索引不超出範圍,因此可以更新?
嗨Bakuriu。我添加了模式代碼,以便您可以看到我想要實現的目標。 – Deepend 2014-10-06 17:32:09
@Deepend是的,從現在發佈的代碼中可以清楚地看出問題是我在回答中描述的。你有'圖像= []',之後'用於步驟(5,6,7):images [step-5] = something'這意味着循環嘗試執行'images [0] = something',正如我所說,由於'圖像'是空的,會引發錯誤。但是我並沒有真正明白你想要達到什麼目的。你的代碼試圖在某個時候使用'images [8]',但'images'在那段代碼中不會有8個元素。 – Bakuriu 2014-10-06 20:34:51
我做了一個非常糟糕的工作解釋這一點。基本上,用戶在每個頁面上看到隨機選擇的不同圖像。在三頁這樣的頁面之後,用戶意圖再次看到前三張圖像。 (數據驗證頁面)發生三次,或三個三個組。 – Deepend 2014-10-06 20:38:30