分页不接受dict作为数据 - 不可分类型 [英] Pagination doesn't accept dict as data - unhashable type
本文介绍了分页不接受dict作为数据 - 不可分类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用Django分页分页文档。但是我收到这个错误:
I'm trying to use Django pagination Pagination Docs. But I'm receiving this error:
TypeError at /
unhashable type
这主要是因为我使用字典作为我的对象而不是查询集。
我想知道是否有办法把我的字典变成一个可哈希的对象。
Which is basically because I'm using a dictionary as my object and not a queryset. I would like to know if there is a way to turn my dictionary a hashable object.
这是我在模板中的dict:
This is my dict in template:
{% for key, values in prodmatrix.items %} <li class="span3">
<div class="product-box">
<span class="sale_tag"></span>
<p><a href="{% url 'product_detail' slug=values.3.0 %}"><img src="{{ STATIC_URL }}{{values.1.0}}" alt="" /></a></p>
<a href="{% url 'product_detail' slug=values.3.0 %}" class="title"><h4>{{ values.0.0 }}</h4></a><br/>
<p class="category"><a href="{% url 'product_detail' slug=values.3.0 %}">{{values.2.}} {{values.2.1}} {{values.2.2}}</a></p>
</div>
</li>
{% endfor %}
这是我的观点:
def home(request):
if request.user.is_authenticated():
print "login"
user = request.user
prods = Product.objects.all()
i = 0
print 'numero de produtos ' + str(len(prods))
prodmatrix = {}
for prod in prods:
# 0 1 2 3
prodmatrix[str(i)] = [[prod.name], [prod.image], [], [prod.slug]]
reviews = Review.objects.filter(product=prod.id) # ^ this is for tags
print str(len(reviews))
if len(reviews) != 0:
for review in reviews:
rev_alltags = review.tag.all()
for tags in rev_alltags[:3]: #
print tags.name
prodmatrix[str(i)][2].append(tags.name) # append only tags
print str(i)
i = i + 1
paginator = Paginator(prodmatrix, 2)
page = request.GET.get('page')
try:
prodmatrix2 = paginator.page(page)
except PageNotAnInteger:
prodmatrix2 = paginator.page(1)
except EmptyPage:
prodmatrix2 = paginator.page(paginator.num_page)
return render(request, 'home.html',{'prodmatrix2':prodmatrix})
推荐答案
使用 tuple
而不是 dict
,如下所示:
Use tuple
instead dict
, like this:
# convert `dict` to `tuple`:
prodmatrix = tuple(prodmatrix)
paginator = Paginator(prodmatrix, 2)
# or this
paginator = Paginator(prodmatrix.items(), 2)
page = request.GET.get('page')
try:
prodmatrix2 = paginator.page(page)
except PageNotAnInteger:
prodmatrix2 = paginator.page(1)
except EmptyPage:
prodmatrix2 = paginator.page(paginator.num_page)
return render(request, 'home.html',{'prodmatrix2':prodmatrix})
在你的模板中,你需要调用attrs和方法元组索引(key = 0,value = 1)
And in you template, you need call the attrs and method by index of tuple (key=0, value=1)
这篇关于分页不接受dict作为数据 - 不可分类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文