Django how to show previous and next button only for related blog post?

In my blog details page I want to add next and previous button for only related blog post. Assume I write three blog on python and two on java. If user on java tutorial-1 details page then I want to show next button for move on java tutoral-2 page and also want previous button to go back java-tutorial-1 page.

#most important note I don’t want to show next button if he is on java-tutorial-2 page as I have only two blog post on java. So I want to show previous and next button only for related blog post not for my all blog post. see the layout below for better understand.


-------Blog Title----------parent object---------------button---------------------------
-    python tutorial-1------->No --------------------->want only next button            |
-    python tutorial-2------->python tutorial-1------->want next and previous button    |  
-    python tutorial-3------->python tutorial-2-------->want only previous button       |    
-    java tutorial-1--------->No ---------------------->want only next button           |
-    java tutorial-2---------->java tutorial-1--------->want only previous button       |

here is my code:

 class Blog(models.Model):
   blog_title = models.CharField(max_length=255)
   blog_parent = models.ForeignKey(
    'self', on_delete=models.CASCADE, blank=True, null=True)

def blogDetails(request, slug=None):
    blog = Blog.objects.filter(blog_slug=slug)
    context = {"blog": blog}
    return render(request, 'blog/blogDetails.html', context)

Is the first one of a set identified by the blog_parent field being null?

Is the last one of a set identified by not having any other Blog related to the current Blog

If so, you can use that information to determine whether or not you want to render a previous or next button, and what the links would be.

1 Like

KenWhitesell Now I added next button but can’t figure how to add previous button. I added parent from my first object to before last one. see the layout for better understood

      blog title             parent object                next button
(python tutorial - 1 )---->(python tutorial-2)----- >successfully added next button
(python tutorial-2 )------>(python tutorial-3)----- >successfully added next button
(python tutorial-3)-------> Null-------> No button as no parent 

my html:



{%if  i.blog_parent %}
<a href="{% url 'blog:blogDetails' i.blog_parent.blog_slug  %}"  id="next_button">next_button</a>


Now I want to add previous button from my second blog post to last blog post. How to do that? any idea?

You can check the existance of an object related to another object through the related manager.

For example, if you have an instance of Blog named a_blog, then you can check to see if there’s a Blog with blog_parent = a_blog as:

Keep in mind that it’s possible to have many such relationships. To continue this example:
returns the list of all Blog with blog_parent referring to a_blog.

1 Like