Python 如何在django中的views.py中创建循环
我不想在单独的变量中重复Python 如何在django中的views.py中创建循环,python,html,django,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
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)
在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)
你可以这样做
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)
有人会回答我的问题吗?我已经补充了一个答案,这是另一个问题。检查静态目录中是否存在映像。映像存在。我已经编辑了我的代码。我的代码中遗漏了一些东西。检查并告诉我。