0
votes

I'm building a simple blog app using Django. This app has a main template blog.html which is shared between the following views:

  • blog (url: /blog/[page number])
    Main page of the blog, displays the last articles

  • search (url: /search/<query>/[page number])
    Will display the articles who match the query

  • category (url: /category/<category name>/[page number])
    Will display the articles from the given category

Each a this views provides the template blog.html with an object page obtained using the function Paginator each time with a different objects list (depending on the view).

Here is my problem:
The template blog.html contains a pager

<ul class="pager">
    {% if page.has_previous %}
        <li class="previous">
            <a href="{{ url_previous_page }}" class="btn btn-primary" >&larr; Older</a>
        </li>
    {% endif %}

    {% if page.has_next %}
        <li class="next">
            <a href="{{ url_next_page }}" class="btn btn-primary" >Newer &rarr;</a>
        </li>
    {% endif %}
</ul>

How can I define in an elegant way the values of url_next_page and url_previous_page in all the views?

1

1 Answers

0
votes

You shouldn't really need to supply the links for the next and previous buttons like that. I would suggest changing your pagination code to be something like this:

<div class="pagination-wrap">
    <span class="pagination-links">
        {% if page_obj.has_previous %}
            <a href="?page={{ page_obj.previous_page_number }}" class="pagination-nav previous"></a>
        {% endif %}
        <span class="current">
            {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}
        </span>
        {% if page_obj.has_next %}
            <a href="?page={{ page_obj.next_page_number }}" class="pagination-nav next"></a>
        {% endif %}
    </span>
    <div>{{ page_obj.start_index }} to {{ page_obj.end_index }} of {{ page_obj.paginator.count }}</div>
</div>

In your views, all you need to specify is the number of objects to paginate by with paginate_by = 15.

If you really want to, you could create a mixin for your list views to use which has a method that could return the url you want.