Reputation: 2623
I would like to hide the Next
button in my blog if there is no next blog post available.
Is there some kind of built-in method to check has_next
has_previous
or do I need to create some logic in my view and extend the template with let's say {% if Foo %} show button {% endif %}
?
views.py
def render_post(request, id):
category_count = get_category_count()
most_recent = Post.objects.order_by('-timestamp')[:3]
post = get_object_or_404(Post, id=id)
next_post_id = int(id) + 1
previous_post_id = int(id) - 1
PostView.objects.get(post=post)
context = {
'post': post,
'id': id,
'next_post_id': next_post_id,
'previous_post_id': previous_post_id,
'most_recent': most_recent,
'category_count': category_count,
}
return render(request, 'post.html', context)
html
<div id="button-wrapper">
<button class="buttons" type="submit"><a href="/post/{{previous_post_id}}">Previous</a></button>
<button class="buttons" type="submit"><a href="/post/{{next_post_id}}">Next</a></button>
</div>
Upvotes: 0
Views: 81
Reputation: 2192
You could do it by checking that the previous/next posts exist and returning the results in the context:
views.py
def render_post(request, id):
category_count = get_category_count()
most_recent = Post.objects.order_by('-timestamp')[:3]
post = get_object_or_404(Post, id=id)
next_post_id = int(id) + 1
previous_post_id = int(id) - 1
try:
previous_post_exists = Post.objects.filter(id=previous_post_id).exists()
except Post.DoesNotExist:
previous_post_exists = False
try:
next_post_exists = Post.objects.filter(id=next_post_id).exists()
except Post.DoesNotExist:
next_post_exists = False
context = {
'post': post,
'id': id,
'next_post_id': next_post_id,
'previous_post_id': previous_post_id,
'previous_post_exists': previous_post_exists,
'next_post_exists': next_post_exists,
'most_recent': most_recent,
'category_count': category_count,
}
return render(request, 'post.html', context)
You would then need to check those values in your template:
html
<div id="button-wrapper">
{% if previous_post_exists %}
<button class="buttons" type="submit"><a href="/post/{{previous_post_id}}">Previous</a></button>
{% endif %}
{% if next_post_exists %}
<button class="buttons" type="submit"><a href="/post/{{next_post_id}}">Next</a></button>
{% endif %}
</div>
Upvotes: 2