Software Dev
Software Dev

Reputation: 1102

Django Pagination Keep Current URL Parameters

I am developing a blog website using Django. On the home page, I have a list of posts, and they are viewed using pagination. On the same home page, I also have the functionality to do a text search (i.e. search for posts with a given text).

For example, if I search for "hello", then the URL is: http://localhost:8000/?q=hello. Then, I want to go to the second page in the pagination, and I expect the URL to look like this: http://localhost:8000/?q=hello&page=2. However, instead, I get this URL: http://localhost:8000/?page=2.

So, basically, when I navigate through pages, I want my pagination to keep the existing "q" parameter in the current URL. The problem is that the "q" parameter is gone when navigating though the pages.

How do I fix this?

This is my pagination:

<div class="pagination">
    <span class="step-links">
    {% if page.has_previous %}
        <a href="?page={{ page.previous_page_number }}"><i class="previous fa fa-arrow-left fa-lg"></i></a>
    {% endif %}
        <span class="current">
      {{ page.number }} of {{ page.paginator.num_pages }}
    </span>
        {% if page.has_next %}
            <a href="?page={{ page.next_page_number }}"><i class="next fa fa-arrow-right fa-lg"></i></a>
        {% endif %}
    </span>
</div>

Upvotes: 4

Views: 2248

Answers (1)

kvothe__
kvothe__

Reputation: 661

Here is one way to fix it.

views.py

def your_view(request):
    ....
    query = request.GET.get('q') # Query or None
    ...
    context = {'query': query}

Add {% if query %}&q={{ query }}{% endif %} in your a tag

templates

<a href="?page={{ page.previous_page_number }}{% if query %}&q={{ query }}{% endif %}">
    <i class="previous fa fa-arrow-left fa-lg"></i>
</a>

Upvotes: 4

Related Questions