boyenec
boyenec

Reputation: 1617

Django how to add next button for related Blog post?

I have an blog list page where I listed all of my blog. Now I want to implement next button in my blog details page for move on next blog post if any blog have child object. Assume I have 10 blog post where 5 blog post related to “python tutorial” so in my blog details page I want to add next button for this five blog post. So user can click on next button and go to next tutorial until reach 5th number of tutorial. If any blog post don’t have any related blog then there will be not next button. You can think as a youtube playlist where all related topics included in a single playlist. how to da that in django?

here is my model:

Class Blog(models.Model):
      blog_title =  models.CharField(max_length=300, unique=True)

views.py

def BlogDetail(request, slug=None):
    template_name = 'blog/blog_details.html'
    blog = None
    if slug is not None:
        blog = get_object_or_404(Blog, slug=slug)
    else:
        blog = None
   ....others code

Upvotes: 0

Views: 544

Answers (1)

SimbaOG
SimbaOG

Reputation: 507

What you can do is:

in views.py:

def BlogDetail(request, slug=None):
    template_name = 'blog/blog_details.html'
    blog = None
    if slug is not None:
        blog = get_object_or_404(Blog, slug=slug)
    else:
        blog = None
    related_objects = Blog.objects.filter(#your query to get related title)
    
    #while returning at it to your dictionary to pass this related object
    #if you had a dictionary add a new key 'related_posts'
    return render(request, 'your_template.html', {'data': data, 'related_posts':related_objects}

Please Note: that 'data' in the code above is the existing data you were returning

in your HTML template:

#your existing template as follow and you can add
{% for posts in related_posts %}
<a href={% url 'YOUR URL FOR BlogDetail function' posts.id %}>NEXT POST {{forloop.counter}} </a>
{% endfor %} 

Upvotes: 1

Related Questions