I am having issues getting results when clicking on page 2 and above - most likely due to url issues. I have a list of names and if I search on e.g. "John" I want them to be separated by pages if number of names > e.g. 10.
My Views are as follows: (searching works fine)
def name_search(request):
if 'q' in request.GET:
q=request.GET.get('q', '')
pvt_list = pvt_data.objects.filter(full_name__icontains=q)
#Pagination
p = Paginator(pvt_list, 10) # Show 10 contacts per page.
page_num = request.GET.get('page', 1)
try:
page = p.page(page_num)
except PageNotAnInteger:
page = p.page(1)
except EmptyPage:
page = p.page(1)
context = {'items' : page}
return render(request, 'home/name_search.html', context)
else:
return render(request, 'home/name_search.html')
My urls.py file is
urlpatterns = [
...
path('name_search', views.name_search, name='name_search'),
...
]
My html file is
{% for pvt in items %}
{{ pvt.full_name }}
{% endfor %}
<div class="pagination">
<span class="step-links">
{% if items.has_previous %}
<a href="?page={{ items.previous_page_number }}">previous</a>
{% endif %}
<span class="current">
Page {{ items.number }} of {{ items.paginator.num_pages }}.
</span>
{% if items.has_next %}
<a href="?page={{ items.next_page_number }}">next</a>
{% endif %}
</span>
</div>
When I search, I get the following link 'http://127.0.0.1:8000/name_search?q=John' with the first 10 names correct.
When I click on next button I get the following link: http://127.0.0.1:8000/name_search?page=2
Changing the link manually to http://127.0.0.1:8000/name_search?q=John/page=2 does not work...
Any response is appreciated :-)
a solution might be to add your search parameter to your href. so instead of:
<a href="?page={{ items.next_page_number }}">next</a>
try:
<a href="?q={{ q }}&page={{ items.next_page_number }}">next</a>