其他分享
首页 > 其他分享> > 八、七天入门Django开发 - Django 实现博客上下篇跳转

八、七天入门Django开发 - Django 实现博客上下篇跳转

作者:互联网

前言
实现上下篇博客文章跳转



定制bootstrap 页面

去到官网,选择组件 - 翻页,把代码复制过来,做微调。


在 blog/detail.html 中加入翻页代码

    <nav aria-label="...">
  <ul class="pager">
    <li><a href="/blog/detail/{{ previous_article.article_id }}">上一篇:{{ previous_article.title }}</a></li>
    <li><a href="/blog/detail/{{ next_article.article_id }}">下一篇:{{ next_article.title }}</a></li>
  </ul>
</nav>



修改视图函数

myblogs/views.py

# 获取博客详情页函数
def get_detail_page(request, article_id):
    all_article = Article.objects.all()  # 获取所有文章
    curr_article = None
    previous_index = 0
    next_index = 0
    previous_article = None
    next_article = None

    for index, article in enumerate(all_article):  # 遍历循环
        if index == 0:
            previous_index = 0
            next_index = index + 1
        elif index == len(all_article) - 1:  # 最后一篇文章的时候,点击下一篇,还是最后一篇
            previous_index = index - 1
            next_index = index
        else:
            previous_index = index - 1
            next_index = index + 1
        if article.article_id == article_id:
            curr_article = article
            previous_article = all_article[previous_index]
            next_article = all_article[next_index]
    return render(request, 'blog/detail.html',
                  {
                      'curr_article': curr_article,  # curr_article 是字典 curr_article 的值,将渲染回blog/detail.html模板
                      'previous_article': previous_article,
                      'next_article': next_article
                  }
                  )



代码是用到了python内置函数enumerate

python enumerate用法:

enumerate()说明:


例子:

既要遍历索引又要遍历元素时

list = ["my", "name", "is", "caihua"]
for index, item in enumerate(list):
    print(index, item)
    
"""
结果:
0 my
1 name
2 is
3 caihua

"""

以上实现了上下篇博客的跳转

标签:index,七天,curr,跳转,Django,enumerate,article,next,previous
来源: https://www.cnblogs.com/wwho/p/15689487.html