我正在尝试使用Django pagination分页文档。但我收到此错误:
TypeError at / unhashable type
这基本上是因为我使用字典作为对象而不是查询集。我想知道是否有一种方法可以将字典变成可哈希的对象。
这是我在模板中的字典:
{% 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,如下所示:
tuple
dict
# 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})
在模板中,您需要按元组的索引(键= 0,值= 1)调用attrs和方法