Django简单博客实战(五)--- 文章详情页的上下篇

实现上一篇和下一篇

项目地址:https://github.com/ylpxzx/lifeblog

  1. 视图中定义上一篇下一篇逻辑
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
  1. 模板判断是否有上一篇和下一篇
{% 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 %}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

狼性书生

谢谢鼓励!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值