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.
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 %}
This is my view:
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})
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})
And in you template, you need call the attrs and method by index of tuple (key=0, value=1)
来源:https://stackoverflow.com/questions/21870430/pagination-doesnt-accept-dict-as-data-unhashable-type