前言
本章主要讲述 【关于我】 页面的具体实现,以及之前咱们遗留的 【文章详情页上一篇/下一篇跳转bug的解决】
- ps:那【关于我】界面的话,就很简单,都是写死的数据,只需要配下路由,自己简单将前端文案改一下就行了
这里我主要讲下【上一篇/下一篇】bug解决思路
环境:
- Pycharm
- python3.6
- mysql 5.7
- django 2.0.13
一、新功能项目概览
二、上一篇/下一篇bug解决
1、article/views.py
- 直接在原来的文章详情视图函数中添加逻辑,我在代码里面写了注释,大家可以详细看下注释里标的【第3点】
from django.shortcuts import render
# Create your views here.
from article.models import Article
"""
文章相关视图函数
"""
def article_detail(request):
"""
通过id查看文章详情
:param request:
:return:
"""
# 拿到当前文章id
article_id = request.GET.get('id')
# print("当前文章id类型:", type(article_id))
# 根据id拿到当前文章
current_article = Article.objects.get(pk=article_id)
# 1、浏览量同步新增:点击一次,浏览量同步加1
current_article.click_num += 1
current_article.save()
# 2、查询相关文章:即对应标签里的前6条数据
tags_list = current_article.tags.all() # 首先拿到标签列表
# 定义【相关文章】list
about_article_list = []
for tag in tags_list:
# 遍历拿到该文章对应标签里的文章列表
for about_article in tag.article_set.all():
# 文章不存在list里且少于6篇,则放到list中
if about_article not in about_article_list and len(about_article_list) < 6:
about_article_list.append(about_article)
# print("about_article_list:", about_article_list)
# 3、拿到上一篇/下一篇文章对象
all_article = Article.objects.all() # 拿到所有文章
print("all_article:", all_article)
previous_index = 0
next_index = 0
previous_article = None
next_article = None
# enumerate将其组成一个索引序列,利用它可以同时获得索引和值
for index, article in enumerate(all_article):
# 当index为0,即当前文章为第一篇,第一篇文章没有上一篇,默认索引为0,下一篇则为index+1
if index == 0:
previous_index = 0
next_index = index + 1
# 当index为总长度-1时,即当前文章为最后一篇,上一篇为index-1,下一篇为当前文章
elif index == len(all_article) - 1:
previous_index = index - 1
next_index = index
# 否则,当index有上一篇/下一篇时,上一篇为index-