Django template : Need 2 values to unpack in for l

2019-07-07 17:23发布

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 !

3条回答
女痞
2楼-- · 2019-07-07 17:49

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})
查看更多
狗以群分
3楼-- · 2019-07-07 17:49

The context passed to render should be a dict

return render(request, 'accounts/page.html', {'list': list})
查看更多
Emotional °昔
4楼-- · 2019-07-07 18:00

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})
查看更多
登录 后发表回答