我想在模板中打印列表......
@login_required
def upload_view(request):
template_var = {}
settings = Tracks.objects.filter(album__exact=None).values_list('file', flat=True)
for setting in settings:
list_setting = setting.split("/", 4)
print_setting = str(list_setting[4])
template_var["trackfiles"] = print_setting
pprint.pprint(template_var["trackfiles"])
return render_to_response('tracks/test.html', template_var ,context_instance=RequestContext(request))
pprint控制台日志的输出是
Django version 1.7, using settings 'audiotube.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
'github-ninja.png'
'sisters.jpg'
'blackwhite.jpg'
'altAlgOdLaLnLAYmJZF6CP1vwJCioRq6cT_NvkinlaLtBBS.jpg'
[15/Sep/2014 04:47:10] "GET /app/upload-tracks HTTP/1.1" 500 178171
我想将这些输出打印到页面中。我试过html {{ trackfiles }}
只打印一个输出(最后一个.jpg),但我需要整个列表进入模板。然后我试过
{% for tracks in trackfiles %}
{{ tracks }}
{% endfor %}
上面的代码也不起作用,我在这里缺少什么?
答案 0 :(得分:0)
模板中的代码很好,问题出在python代码中。当您迭代设置时,每次执行
template_var["trackfiles"] = print_setting
所以你要覆盖字典项目' trackfiles'每次都有' print_setting'的当前值,所以最后你拥有的是最新值。
答案 1 :(得分:0)
您需要先启动列表对象。那必须是" print_settings"你的函数中的对象。因此,如果您在 upload_view()函数的顶部添加print_settings = list()
,并使用print_setting = str(list_setting[4])
更改行print_setting.append(str(list_setting[4]))
,那就是您的方式一个可迭代的列表。
@login_required
def upload_view(request):
print_setting = [] # or list()
template_var = {}
settings = Tracks.objects.filter(album__exact=None).values_list('file', flat=True)
for setting in settings:
list_setting = setting.split("/", 4)
print_setting.append(str(list_setting[4]))
template_var["trackfiles"] = print_setting
pprint.pprint(template_var["trackfiles"])
return render_to_response('tracks/test.html', template_var, context_instance=RequestContext(request))
您可能需要阅读about lists