Pagination django listview

Question:

I have to do pagination by 3 items per page,i have this code.When i clicked on the next button, link is changing, but on the page,its not.I tried a few examples from stackoverflow but it doesnt usefull

views.py

class ShowPost(ListView):
    model = Posts
    template_name = 'posts/allposts.html'
    paginate_by = 3
    page_kwarg = 'posts'

urls.py

urlpatterns = [
    path("addpost/", AddPost.as_view(), name='post'),
    path("all_posts/", ShowPost.as_view(), name='show_post')
]

allposts.html

<!DOCTYPE html>
{% load thumbnail %}
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<ul>
    {% for object in object_list %}
    <li>Owner: {{ object.owner }}</li>
    <li>Phone: {{ object.phone_number }}</li>
    <li>Title: {{ object.title }}</li>
    <li>Text: {{ object.text }}</li>
    <li>Type: {{ object.type }}</li>
    <li>Price: {{ object.price }}</li>
    <li>Date: {{ object.created }}</li>
    <p>
      {% if object.image %}
      <img src="{% thumbnail object.image 200x200 crop %}" alt="" />
      {% endif %}
      </p>
  <hr/>
    <!-- If object_list is empty  -->
    {% empty %}
    <li>No objects yet.</li>
    {% endfor %}
  <br>
  Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}
  <ul style="margin-left: 10px;" class="pagination">
    {% if page_obj.has_previous %}
    <li><a href="?page1">&laquo; first</a></li>
    <li><a href="?page={{ page.obj.previous_page_number }}">previous</a></li>
    {% endif %}
    {% if page_obj.has_next %}
    <li><a href="?page={{ page_obj.next_page_number }}">next</a></li>
    <li><a href="?page={{ page_obj.paginator.num_pages }}">last</a></li>
    {% endif %}
  </ul>
</ul>
</body>
</html>
Asked By: makim

||

Answers:

Based on the doc, I tested your code and below you can find a simple version of html, change it based on your need. For the view you should remove page_kwarg = 'posts'. Make sure that you have more post objects than 3!

{% for post in page_obj %}
    {{ post.title }}<br>
{% endfor %}

<div class="pagination">
    <span class="step-links">
        {% if page_obj.has_previous %}
            <a href="?page=1">&laquo; first</a>
            <a href="?page={{ page_obj.previous_page_number }}">previous</a>
        {% endif %}

        <span class="current">
            Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
        </span>

        {% if page_obj.has_next %}
            <a href="?page={{ page_obj.next_page_number }}">next</a>
            <a href="?page={{ page_obj.paginator.num_pages }}">last &raquo;</a>
        {% endif %}
    </span>
</div>
Answered By: A D