Issue
How use pagination and filtering together? I have problem because they dont want to work eachother, without filter pagination work but with filter my app have crashes. I know they are some examples how do this on stack overrflow, and it seems thaat problem is in html file but this examples arent fully understandable for me, i would be appreciate if someone would show me what i must change in my code then i would understand this better. I am currently learning Django and still i have problems with understanding someones else code, i understand very well what ive done in my code but when i see someone else code that looks diffrent than mine then i dont know whats going on.
views.py
def Product_list(request, category_slug=None):
category=None
categories=Category.objects.all()
products=Product.objects.all()
paginator=Paginator(products, 6)
page=request.GET.get('page')
products=paginator.get_page(page)
if category_slug:
category=get_object_or_404(Category, slug=category_slug)
products=products.filter(category=category)
return render(request, 'shop/product/Product_list.html',
{'products':products, 'category':category,
'categories':categories,})
product_list.html
<div class='paginator'>
{% if products.has_previous %}
<a href='?page1'><<</a>
<a href='?page={{products.previous_page_number}}'><</a>
{%endif%}
{%for num in products.paginator.page_range%}
{% if products.number == num %}
<strong>{{num}}</strong>
{%elif num > products.number|add:'-3' and num < products.number|add:'3' %}
{{num}}
{%endif%}
{%endfor%}
{% if products.has_next %}
<a href='?page={{products.paginator.num_pages}}'>>></a>
<a href='?page={{products.next_page_number}}'>></a>
{%endif%}
</div>
Solution
You can only filter a QuerySet
. But in your view, you're first paginating (so products
is now a Page
) and then trying filter that Page
object. You should only paginate after you've got your final QuerySet
with all filters applied.
Answered By - dirkgroten
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.