[Answered ]-I have a search function which render another page with search results and i have implemented pagination within this function but it shows me an error

1👍

Return something if query==False:

def search_user(request):
    query = request.GET.get("q")
    context ={}
    if query:
        users = User.objects.filter(Q(username__icontains=query))
        if users:
            page = request.GET.get('page', 1)
            paginator = Paginator(users, 1)
            try:
                users = paginator.page(page)
            except PageNotAnInteger:
                users = paginator.page(1)
            except EmptyPage:
                users = paginator.page(paginator.num_pages)
            context={'users': users}
            return render(request,'user/search.html',context)
        else:
            messages.warning(request,'User matching query does not exist.')
            return redirect('acc_req_list')
    else:
        return redirect('URL')

Update:

search.html:

Pass q = {{request.GET.q}}

    {% if users.has_other_pages %}
        <ul class="pagination">
          {% if users.has_previous %}
            <li class="page-item active">               
     ➡➡➡➡<a class="page-link" href="?page={{ users.previous_page_number }}&q={{ request.GET.q }}">pre</a>
            </li>
          {% else %}
            <li class="page-item disabled"><span></span></li>
          {% endif %}
          {% for i in users.paginator.page_range %}
            {% if users.number == i %}
              <li class="page-item"><span style="z-index: 1; position: relative; display: block;padding: 0.5rem 0.75rem; margin-left: -1px; line-height: 1.25; color: #f7efef; background-color: #F64E60; border: 1px solid #E4E6EF;">{{ i }} <span class="sr-only" >(current)</span></span></li>
            {% else %}
     ➡➡➡➡<li class="page-item"><a class="page-link" href="?page={{ i }}&q={{ request.GET.q }}">{{ i }}</a></li>
            {% endif %}
          {% endfor %}
          {% if users.has_next %}
            <li class="page-item active">
     ➡➡➡➡<a class="page-link" href="?page={{ users.next_page_number }}&q={{ request.GET.q }}">Next</a>
            </li>
          {% else %}
            <li class="page-item disabled"><span></span></li>
          {% endif %}
        </ul>
    {% endif %}

Leave a comment