0
votes

I have 6 posts in my database and I want to show 3 posts per page. Everything is working without any error but when I click 'next page' link, same posts are reloading. Here the steps,

http://127.0.0.1:8000/blog/

is loading succesfully and there are 3 posts in page. Also, 'next page' link is also on the bottom of the page as expected.

When I click nextpage, URL is changing into:

http://127.0.0.1:8000/blog/?page=2

But as I said, first page's posts are reloading.

url.py:

path('',views.getPosts,name="bloghome"),
path('/<int:selected_page>/',views.getPosts,name="bloghome"),

view.py function about pagination:

def getPosts(request,selected_page=1):
    posts = Posts.objects.all()
    pages = Paginator(posts,3) #Show 3 post per page
    try:
        returned_page = pages.get_page(selected_page)
    except EmptyPage:
        returned_page = pages.page(pages.num_pages)   
    return render(request,'blog.html',{'page':returned_page,
                                       'posts':returned_page.object_list
                                        })

Post listing page's template:

{% extends 'blog_mainpage_assets.html' %}
{%load static%}

    {% block document_body%}
        <div class="container" style="margin-top:40px;">
                {%for post in posts%}
                <div class="post">
                        <div class="baslikveyazi">
                            <div class="baslik_2">
                                <h2><a href="{% url 'post_detail' post.slug %}">{{post.post_title}}</a></h2>
                            </div>
                            <div class="yazi_2">
                                <div style="word-wrap: break-word;"><p style="font-size:20px;line-height:2;">{{post.post_body|truncatechars:100}}</p></div>
                            </div>
                        </div>
                </div>

                {%endfor%}

                {% if page.has_previous %} 
                <a href="{% url 'bloghome' %}?page={{page.previous_page_number}}">Back</a>
                {% endif %}                
                {% if page.has_next %}                
                <a href="{% url 'bloghome' %}?page={{page.next_page_number}}">Next</a>
                {% endif %}


        </div>
    {% endblock document_body%}
1

1 Answers

0
votes

Your second URL takes the form /blog/<page>/ but this is not the URL you construct in your link. Your link looks like /blog/?page=2. A query argument (?page=2) is completely different from a URL path (/2/) and so your selected_page in your view will never be anything other than 1.

I would drop the second URL from your URL config, and then check the query argument in the view:

def getPosts(request):
    posts = Posts.objects.all()
    pages = Paginator(posts, 3) #Show 3 post per page
    selected_page = request.GET.get('page', 1)
    try:
        returned_page = pages.get_page(selected_page)
    except EmptyPage:
        returned_page = pages.page(pages.num_pages)