如何在Django中的views.py中循环播放

时间:2019-07-11 04:05:25

标签: python html django

我不想在单独的变量中一次又一次地重复Destination函数。我尝试制作不同的变量,并将其等于Destination(),但没有用。如何在其中循环,这样我就不必重复了?

def index(request):
    dest1 = Destination()
    dest1.desc = 'Hello, How are you?'
    dest1.img = '01.jpg'

    dest2 = Destination()
    dest2.desc = 'Hello, HOw are you?'
    dest2.img = '02.jpg'

    dests1 = [dest1, dest2] # that was missing.

    context = {
       'dests1': dests1,
       'dests2': dests2,
}

return render(request, 'index.html',context)

2 个答案:

答案 0 :(得分:2)

在def index(request)函数内的

循环直至所需的Destination()对象并将数据保存在列表中的次数,您可以从该列表中稍后检索数据。您还可以更轻松地创建图像列表,对事物的描述

numberOfDestinationNeeded = 4 # change this number according to your need
destList = []
for i in range(numberOfDestinationNeeded):
    destObj = Destination()
    destObj.desc = "dfsfs"
    destObj.img = '02.jpg'
    destList.append(destObj)

答案 1 :(得分:0)

您可以执行以下操作。

no_of_destinations = 4 #Some number.
context = {}
for index in range(1, no_of_destinations+1):
    dest = Destination()
    dest.desc = 'How are you?'
    dest.img = '0{}.jpg'.format(index)
    context['dest{}'.format(index)] = dest

return render(request, 'index.html',context)