脚本宝典收集整理的这篇文章主要介绍了八、七天入门Django开发 - Django 实现博客上下篇跳转,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
前言 实现上下篇博客文章跳转
去到官网,选择组件 - 翻页,把代码复制过来,做微调。
<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
enumerate()说明:
enumerate()是python的内置函数
enumerate在字典上是枚举、列举的意思
对于一个可迭代的(iterable)/可遍历的对象(如列表、字符串),enumerate将其组成一个索引序列,利用它可以同时获得索引和值。 enumerate多用于在for循环中得到计数, 例如对于一个seq,得到:(0, seq[0]), (1, seq[1]), (2, seq[2])
enumerate()返回的是一个enumerate对象
既要遍历索引又要遍历元素时
list = ["my", "name", "is", "caihua"]
for index, item in enumerate(list):
print(index, item)
"""
结果:
0 my
1 name
2 is
3 caihua
"""
以上实现了上下篇博客的跳转
以上是脚本宝典为你收集整理的八、七天入门Django开发 - Django 实现博客上下篇跳转全部内容,希望文章能够帮你解决八、七天入门Django开发 - Django 实现博客上下篇跳转所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。