I'm Django beginner so I'm stuck in class-based pagination and I have followed many posts about pagination but unfortunate couldn't solve this error.
if i search "love" in search box so URL become like this
and results show with pagination function but when i click on next pagination button then query get remove and url become like this
and error raise: Invalid page (2): That page contains no results
anyone can tell me from where I'm wrong? thanks
Views.py
from django.views import generic
from .models import Album, Song
from django.db.models import Q
class Search(generic.ListView):
template_name = 'music/search.html'
paginate_by = 5
def get_queryset(self, *args, **kwargs):
queryset_list = Song.objects.all()
query = self.request.GET.get('q')
if query:
queryset_list = queryset_list.filter(
Q(song_title__icontains=query)|
Q(file_type__icontains=query)
).distinct()
if not query:
queryset_list = Song.objects.none()
return queryset_list
return queryset_list
search.html
{% if object_list %}
<h1>Search result..</h1>
{% for i in object_list %}
<p>{{i.song_title}}</p>
{% endfor %}
<!-- pagination-->
{% if is_paginated %}
<ul class="pagination">
{% if page_obj.has_previous %}
<li><a href="?page={{ page_obj.previous_page_number }}">«</a></li>
{% else %}
<li class="disabled"><span>«</span></li>
{% endif %}
{% for i in paginator.page_range %}
{% if page_obj.number == i %}
<li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li>
{% else %}
<li><a href="?page={{ i }}">{{ i }}</a></li>
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
<li><a href="?page={{ page_obj.next_page_number }}">»</a></li>
{% else %}
<li class="disabled"><span>»</span></li>
{% endif %}
</ul>
{% endif %}
<!-- end pagination-->
{% else %}
<h1>no result found..</h1>
{% endif %}
urls.py
from django.conf.urls import url
from music import views
url(r'^search/$', views.Search.as_view(), name='search')