Django template : Need 2 values to unpack in for loop; got 8

我们两清 提交于 2020-02-24 11:11:47

问题


Through my view I collected some data that I want to bundle together in a list of values that look like this :

data = [(1,2,3,4,5,6,7,8),(1,2,3,4,5,6,7,8),(1,2,3,4,5,6,7,8)]

Then I'll be rendering that to my template to unpack the data to my page :

return render(request, 'accounts/page.html', {'data' : data})

Template goes like this :

{% for a,b,c,d,e,f,g,h in data %}
    <h3>{{a}}</h3>
    <h3>{{b}}</h3>
    #and so on
    #..
    <h3>{{h}}</h3>
{% endfor %}

So the error i get is :

Need 2 values to unpack in for loop; got 8.

Can anyone figure out the source of this error or maybe have a better way of rendering data in bundles ?

Thanks !


回答1:


Be careful to not use list as variable it is depreciated since it is a Python Type Object(reserved)
And the problem is only in your render:

my_list = [(1,2,3,4,5,6,7,8),(1,2,3,4,5,6,7,8),(1,2,3,4,5,6,7,8)]
return render(request, 'accounts/page.html', {'my_list': my_list})



回答2:


The context passed to render should be a dict

return render(request, 'accounts/page.html', {'list': list})



回答3:


You need to zip the list and pass it as a dict:

list = zip([(1,2,3,4,5,6,7,8),(1,2,3,4,5,6,7,8),(1,2,3,4,5,6,7,8)])
return render(request, 'accounts/page.html', {'list':list})


来源:https://stackoverflow.com/questions/51633309/django-template-need-2-values-to-unpack-in-for-loop-got-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!