How to page a search page in Django?

Asked

Viewed 74 times

-1

Hello, I am trying to paginate the results of a search page on Django, but without success. A class based view is responsible:

class SearchResultsView(ListView):
    model = User
    paginate_by = 2
    template_name = 'search.html'
    def get_context_data(self, **kwargs):
        query = self.request.GET.get('q')
        context = super().get_context_data(**kwargs)
        context['page_obj'] = User.objects.filter(name__icontains=query)
        context['quant'] = User.objects.filter(name__icontains=query).count()
        context['search'] = query
        return context 

Where 'q' is the user name the user searches for a search bar

{% extends 'base.html' %}
{% block content %}
<div class='col-md-6'>
  <h2>Temos {{ quant }} usuários com o nome semelhante a "{{search}}"</h2>
<ul class="list-group">
    {% for name in page_obj %}
      <a href="{% url 'name' name.id%}" class="list-group-item list-group-item-action">  {{ name.name }}</a>
    {% empty %}
      <li><h2>Não achamos nada parecido, desculpe.</h2></li>
    {% endfor %}
</ul>
{% if is_paginated %}
    <ul class="pagination justify-content-center" style="margin-top: 10px;">
      {% if page_obj.has_previous %}
        <li class="page-item">
          <a class="page-link" href="?page={{ page_obj.previous_page_number }}" tabindex="-1">Previous</a>
        </li>
      {% endif %}
      {% for num in paginator.page_range %}
          {% if page_obj.number == num %}
            <li class="page-item active"><a class="page-link" href="#">{{num}}</a></li>
          {% else %}
            <li class="page-item"><a class="page-link" href="?page={{num}}">{{num}}</a></li>
          {% endif %}
      {% endfor %}
      {% if page_obj.has_next %}
        <li class="page-item">
          <a class="page-link" href="?page={{ page_obj.next_page_number }}">Next</a>
        </li>
      {% endif %}
    </ul>
  </nav>
  {% endif %}
{% endblock %}

The first page loads normally, the second page gives the following error:

Valueerror at /search/ Cannot use None as a query value

1 answer

0

Hey, your code had a lot of problems. On the server in views.py where you can use the Django Page and combine it as your search and have a search with paged results.

py views.

from django.core.paginator import Paginator
from django.core.paginator import EmptyPage
from django.core.paginator import PageNotAnInteger

class SearchResultsView(ListView):
    model = User
    template_name = 'search.html'
    paginate_by = 2

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        query = self.request.GET.get('q', '')
        list_user = User.objects.filter(name__icontains=query) if query != '' else User.objects.all()
        paginator = Paginator(list_user, self.paginate_by)

        page = self.request.GET.get('page', 1)

        try:
            page_obj = paginator.page(page)
        except PageNotAnInteger:
            page_obj = paginator.page(1)
        except EmptyPage:
            page_obj = paginator.page(paginator.num_pages)

        context['page_obj'] = page_obj
        context['quant']    = list_user.count()
        context['search']   = query
        return context

search html.

{% extends "base.html" %}
{% block content %}
<div class='col-md-6'>
  <h2>Temos {{ quant }} usuários com o nome semelhante a "{{search}}"</h2>
<ul class="list-group">
    {% for name in page_obj %}
      <a href="{% url 'name' name.id%}" class="list-group-item list-group-item-action">  {{ name.name }}</a>
    {% empty %}
      <li><h2>Não achamos nada parecido, desculpe.</h2></li>
    {% endfor %}
</ul>
{% if is_paginated %}
    <ul class="pagination justify-content-center" style="margin-top: 10px;">
      {% if page_obj.has_previous %}
        <li class="page-item">
          <a class="page-link" href="?page={{ page_obj.previous_page_number }}" tabindex="-1">Previous</a>
        </li>
      {% endif %}
      {% for num in paginator.page_range %}
          {% if page_obj.number == num %}
            <li class="page-item active"><a class="page-link" href="#">{{num}}</a></li>
          {% else %}
            <li class="page-item"><a class="page-link" href="?page={{num}}">{{num}}</a></li>
          {% endif %}
      {% endfor %}
      {% if page_obj.has_next %}
        <li class="page-item">
          <a class="page-link" href="?page={{ page_obj.next_page_number }}">Next</a>
        </li>
      {% endif %}
    </ul>
  </nav>
  {% endif %}
{% endblock %}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.