0
votes

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

http://127.0.0.1:8000/search/?q=love

and results show with pagination function but when i click on next pagination button then query get remove and url become like this

http://127.0.0.1:8000/search/?page=2

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 }}">&laquo;</a></li>
            {% else %}
              <li class="disabled"><span>&laquo;</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 }}">&raquo;</a></li>
            {% else %}
              <li class="disabled"><span>&raquo;</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')
1

1 Answers

4
votes

You haven't included your search term in your links, so as you can see the URL doesn't include it and therefore get_queryset returns an empty set. You should make sure you do include it everywhere:

<a href="?q={{ request.GET.q }}&page={{ page_obj.previous_page_number }}">

and similarly for all the other links.