I have a list of projects. When I enter into details of one of them then I would like check others using next page.
The problem I have is that it doesnt matter which one I click on I always start from the first page (first project)
The documentation of Paginator class I found in django docs is very small and I would like to find the way to indicate which page display, ex. if I click on object with id=3 I should see <Page 3 of 8>.
def project_detail(request, id):
projects = Project.objects.all()
paginator = Paginator(projects, 1)
page = request.GET.get('page')
project = paginator.get_page(page)
return render(request,
'portfolio/projects/detail.html',
'project': project})
I woud like to implement this part of code inside:
paginator.page(id)
if it`s posible, but sincerly dont know how.
You can check if page
is an element of request.GET
, if it is not, we return .get_page(id)
instead:
def project_detail(request, id):
projects = Project.objects.all()
paginator = Paginator(projects, 1)
if 'page' in request.GET:
project = paginator.get_page(request.GET['page'])
else:
project = paginator.get_page(id)
return render(
request,
'portfolio/projects/detail.html',
'project': project}
)
That being said, it is not entirely clear to me why you want to do that. It is not guaranteed that an object with pk=5 for example is the fifth element. If you remove elements, there can be "gaps" between the primary keys.
If you want to obtain the page where that element is present, you should determine the page. You can do this with:
def project_detail(request, id):
projects = Project.objects.order_by('pk')
paginator = Paginator(projects, 1)
if 'page' in request.GET:
project = paginator.get_page(request.GET['page'])
else:
page = Project.objects.filter(pk__lte=id).count()
project = paginator.get_page(page)
return render(
request,
'portfolio/projects/detail.html',
'project': project}
)