Tiltled previous and next blog using django class based view

If I open a blog detail, there should be the previous blog and next blog title as a pagination. From Django documentation, I implemented the pagination by page number. But how can I implement the pagination by previous blog and next blog title.

Here is my model.py:

class Post(models.Model):
    title = models.CharField(max_length=250, unique=True)
    slug = models.SlugField(max_length=250, unique=True, null=True, blank=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="blog_posts")
    cover = models.ImageField(upload_to="Uploaded/")
    content = RichTextUploadingField(blank=True, null=True)
    sticker = models.CharField(max_length=50, unique=False, null=True, blank=True)
    published_at = models.DateTimeField(auto_now_add=True)
    updated_on = models.DateTimeField(auto_now=True)
    status = models.IntegerField(choices=STATUS, default=0)
    tags = models.CharField(max_length=400, null=True, blank=True)

    class Meta:
        ordering = ['-published_at']
    
    def __str__(self):
        return self.title
    

views.py

class PostDetail(generic.DetailView):
    model = Post
    template_name = 'blogs/post_detail.html'

post_detail.html

{% extends "blogs/base.html" %}
{% load static %}
{% block post %}
<section class="services">
    <dev class="box-container">
        <div class="box-lg">
            <h3>{{ post.title }}</h3>
            <img src="/Images/{{ post.cover }}"  >
            <hr>
            <small>{{ post.published_at }}</small>
            <p>{{ post.content | safe }}</p>
        </div>
    </dev>
</section>

<!-- Pagination Start -->
<div class="center">
</div>
<!-- Pagination Ends -->
{% endblock post %}

Now please help me how to do the prev-next blog titled pagination like the below image!

titled pagination image

One way you can handle this is to use .get_previous_by_Foo and .get_next_by_Foo you can read more here : https://docs.djangoproject.com/en/2.1/ref/models/instances/#django.db.models.Model.get_next_by_FOO

This is just an idea how you can do it.

{% extends "blogs/base.html" %}
{% load static %}
{% block post %}
<section class="services">
    <dev class="box-container">
        <div class="box-lg">
            <h3>{{ post.title }}</h3>
            <img src="/Images/{{ post.cover }}"  >
            <hr>
            <small>{{ post.published_at }}</small>
            <p>{{ post.content | safe }}</p>
        </div>
    </dev>
</section>

<!-- Pagination Start -->
<div class="center">
{{ post.get_previous_by_published_at.title }}
</div>
<!-- Pagination Ends -->
<div class="center">
{{ post.get_next_by_published_at.title }}
</div>

{% endblock post %}

as i said this just an idea in real life you have to check that next or previous post exists or maybe that post is the last one a thing like that...

Back to Top