Pagination with id in url instead od “?page=”


(Mark) #1

I have an application in Django 1.8 and my problem is the parameter “?page=” in the address. My goal is address in 127.0.0.0.1/blog/1 - and search results. Can I count on a hint?

My urls:

urlpatterns = [
    url(r'^$', MyListView.as_view(), name='list'),
    url(r'/(?P<slug>[-\w]+)/(?P<pk>\d+)$', views.BlogDetailView.as_view(), name='blog_detail'),
]

My view:

class MyListView(ListView):
    model = models.Blog
    queryset = models.Blog.objects.order_by('-pub_date')
    template_name = 'blog/blog_list.html'
    context_object_name = 'blog_list'
    paginate_by = 10

code in template

{% 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 %}

(Vitor Freitas) #2

It looks like the ListView expects a keyword argument named page on the URL.

So you can try something like:

urlpatterns = [
    url(r'^$', MyListView.as_view(), name='list'),
    url(r'^(?P<page>\d+)$', MyListView.as_view(), name='list_page'),
    url(r'(?P<slug>[-\w]+)/(?P<pk>\d+)$', views.BlogDetailView.as_view(), name='blog_detail'),
]
{% if is_paginated %}
  <ul class="pagination">
    {% if page_obj.has_previous %}
      <li><a href="{% url 'list_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="{% url 'list_page' i %}">{{ i }}</a></li>
      {% endif %}
    {% endfor %}
    {% if page_obj.has_next %}
      <li><a href="{% url 'list_page' page_obj.next_page_number %}">&raquo;</a></li>
    {% else %}
      <li class="disabled"><span>&raquo;</span></li>
    {% endif %}
  </ul>
{% endif %}

And your view you shouldn’t need to change anything.