Search code examples
djangodjango-viewsforums

Adding a next/previous button in blog posts


On my page all the blog posts will be showing up. So I wanted to implement a next/previous button to better my page.

def PostLists(request):
    num = request.session.get('num',-5)
    request.session['num'] = num
    num = num + 5
    exp = Post.objects.order_by('-date').all()[num:(num+5)]
    context = {
        'object_list': exp
    }
    if (request.user.is_authenticated):
        return render(request, 'dashboard/postlist.html', context=context)
    else:
        return redirect('login')

I added a next button in my html code which will redirect me to my the same views.py function as shown above and the variable(num) shall increment by 5 thus showing me my next 5 posts. However this seems not to be working as I see the same 5 posts always.

Is there a better way to implement a next/previous button? If so could you please specify that? Thanks a lot!


Solution

  • I think you try to do too much yourself. Django has support for this, it even has a lot of support when rendering lists, and enforcing that the user is logged in.

    We can use a class-based view for this: a ListView:

    from django.contrib.auth.mixins import LoginRequiredMixin
    from django.views.generic import ListView
    
    class PostListView(LoginRequiredMixin, ListView):
        model = Post
        template_name = 'dashboard/postlist.html'
        paginate_by = 5
        queryset = Post.objects.order_by('-date')

    In your dashboard/postlist.html template, then you can add logic to render the buttons. Like for example:

    <!-- render the list -->
    
    {% if is_paginated %}
        {% if page_obj.has_previous %}
            <a href="?page={{ page_obj.previous_page_number }}">previous</a>
        {% endif %}
        {% if page_obj.has_next %}
            <a href="?page={{ page_obj.next_page_number }}">next</a>
        {% endif %}
    {% endif %}

    In the urls.py you can then use the PostListView.as_view() instead of the PostLists. So the ListView will here handle authentication check, slicing, pagination, etc.