Search code examples
pythondjangopaginator

Django : go back to correct paginator page


I have simple blog app that is using paginator for listing articles.

I want to be able to add button in article detail page that will direct user to same page that this article is on.

I want to take slug from current url and send it to paginator so that it directs user to ?page=X where article is on.

I checked paginator docs and didn't find any info on how to retrieve page number of specific object.

my views:

def blog(request):
    posts = Article.objects.all()
    paginator = Paginator(posts, 3) 
    page = request.GET.get('page') 
    posts = paginator.get_page(page) 
    return render(request,'blog.html',{'posts':posts})

def article_id(request,slug):
    articleid = Article.objects.get(slug=slug)
    return render(request, 'blogid.html', {'article':articleid})

my urls:

urlpatterns = [
    url(r'^$', views.blog, name = 'blog'),
    url(r'^(?P<slug>[\w-]+)/$', views.article_id, name = 'article_id'),
   ]

Solution

  • You can get the position of the object via

    position=Article.objects.filter(your_filter_key=your_filter_value).order_by('other_filter_order').count()
    

    Then get the page number via

    items_per_page=yout_items_per_page
    page = int(position/items_per_page)