Django+Python+Bootstrap实现上下篇文章跳转、分页
实现上下篇文章跳转
打开Bootstrap翻页组件页面
复制图中选中的代码修改成我们需要的,放入写好的detail页面下方。
<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_previous.article_id }}">下一篇:{{ next_article.title }}</a></li>
</ul>
</nav>
打开视图层views.py
文件,修改原来写好的get_detail_page
函数。
def get_detail_page(request, article_id):
all_article = Article.objects.all()
current_article = None
previous_article = None
next_article = None
for index, article in enumerate(all_article):
if index == 0:
previous_article_index = 0
next_article_index = index + 1
elif index == len(all_article) - 1:
previous_article_index = index - 1
next_article_index = index
else:
previous_article_index = index - 1
next_article_index = index + 1
if article.article_id == article_id:
current_article = article
previous_article = all_article[previous_article_index]
next_article = all_article[next_article_index]
break
section_list = current_article.content.split("\n")
return render(request, 'blog/detail.html',
{
'current_article': current_article,
'section_list': section_list,
'previous_article': previous_article,
'next_article': next_article
}
)
实现文章分页
-
Bootstrap实现分页按钮
打开Bootstrap官网,找到分页组件
-
设计分页URL
采用GET
请求,获取分页参数。page = request.GET.get('page') if page: page = int(page) else: page = 1 print('page ==', page)
-
使用Django分页组件实现分页功能
进入命令行,输入python manage.py shell
进入Django shell,输入from django.core.paginator import Paginator
命令导入Django分页组件库。
进入views.py
文件,导入分页包‘’from django.core.paginator import Paginator‘’,修改get_index_page
函数。
然后按照上下篇文章跳转修改index.html
文件里面的分页组件。
最新文章列表实现
按时间顺序展示最近三篇文章列表,还是修改get_index_page
函数,修改完成以后,在index.html
里面修改最新文章展示的列表。(原来写的全部list改成你获取到的最新的三篇文章列表)
def get_index_page(request):
page = request.GET.get('page')
if page:
page = int(page)
else:
page = 1
all_article = Article.objects.all()
new_article_list = Article.objects.order_by('-publish_date')[:3]
paginator = Paginator(all_article, 2)
page_num = paginator.num_pages
page_article_list = paginator.page(page)
if page_article_list.has_next():
next_page = page + 1
else:
next_page = page
if page_article_list.has_previous():
previous_page = page - 1
else:
previous_page = page
return render(request, 'blog/index.html',
{
'article_list': page_article_list,
'page_num': range(1, page_num + 1),
'current_page': page,
'next_page': next_page,
'previous_page': previous_page,
'new_article_list': new_article_list
}
)
运行效果如下