八、七天入門Django開發 - Django 實現部落格上下篇跳轉
阿新 • • 發佈:2021-12-14
前言
實現上下篇部落格文章跳轉
定製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()說明:
-
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
"""
以上實現了上下篇部落格的跳轉