实现上一篇和下一篇
项目地址:https://github.com/ylpxzx/lifeblog
- 视图中定义上一篇下一篇逻辑
class PostDetailView(DetailView):
model = Post
template_name = 'detail_post.html'
context_object_name = "post"
pk_url_kwarg = 'post_id'
def get_object(self, queryset=None):
obj = super(PostDetailView,self).get_object()
obj.total_views += 1
obj.save(update_fields=['total_views'])
return obj
def get_context_data(self, **kwargs):
kwargs['author_list'] = Blogger.objects.all()
kwargs['category_list'] = Category.objects.all().order_by('post_category')
kwargs['popular_post'] = Post.objects.all().order_by('-total_views')[:4]
content = super(PostDetailView, self).get_context_data(**kwargs)
num = content['post'].id
# 下一篇,找出id大于当前文章id的文章,升序排序后取第一个,即为下一篇
next_post = Post.objects.filter(id__gt=num).order_by("id")[:1]
if len(next_post) == 0:
content['next_post'] = 0
else:
for next in next_post:
content['next_post'] = next
# 上一篇,找出id小于当前文章id的文章,降序排序后取第一个,即为上一篇
prev_post = Post.objects.filter(id__lt=num).order_by("-id")[:1]
if len(prev_post) == 0:
content['prev_post'] = 0
else:
for prev in prev_post:
content['prev_post'] = prev
return content
- 模板判断是否有上一篇和下一篇
{% if prev_post != 0 %}
<div class="detials">
<p>Prev Post</p>
<a href="{% url 'post:detail' prev_post.id %}"><h4>{{ prev_post.title }}</h4></a>
</div>
{% endif %}
{% if next_post != 0 %}
<div class="detials">
<p>Next Post</p>
<a href="{% url 'post:detail' next_post.id %}"><h4>{{ next_post.title }}</h4></a>
</div>
{% endif %}