|
|
# blog/views.py
|
|
|
from django.shortcuts import render, get_object_or_404
|
|
|
from .models import Post, Category
|
|
|
|
|
|
def index(request):
|
|
|
"""首页视图"""
|
|
|
# LXC: 获取已发布的文章,按创建时间倒序排列,取前10篇
|
|
|
post_list = Post.objects.filter(status='published').order_by('-created_time')[:10]
|
|
|
# LXC: 获取已发布的文章,按浏览量倒序排列,取前5篇作为热门文章
|
|
|
hot_posts = Post.objects.filter(status='published').order_by('-views')[:5]
|
|
|
|
|
|
# LXC: 构建上下文数据,包含文章列表、热门文章、分类信息等
|
|
|
context = {
|
|
|
'post_list': post_list,
|
|
|
'hot_posts': hot_posts,
|
|
|
'category_info': {
|
|
|
'name': '非遗传承',
|
|
|
'label': '',
|
|
|
'desc': '探索南京非物质文化遗产的独特魅力与传承故事'
|
|
|
},
|
|
|
'current_path': request.path,
|
|
|
'current_category_id': None
|
|
|
}
|
|
|
# LXC: 渲染首页模板并返回响应
|
|
|
return render(request, 'blog/index.html', context)
|
|
|
|
|
|
def category_view(request, category_id):
|
|
|
"""分类页面视图"""
|
|
|
# LXC: 根据分类ID获取分类对象,如果不存在则返回404
|
|
|
category = get_object_or_404(Category, id=category_id)
|
|
|
# LXC: 获取热门文章列表
|
|
|
hot_posts = Post.objects.filter(status='published').order_by('-views')[:5]
|
|
|
|
|
|
# LXC: 定义分类映射字典,包含每个分类的标签和描述
|
|
|
category_map = {
|
|
|
1: {'label': '巧夺天工·工艺', 'desc': '探索南京传统手工艺的精湛技艺与匠心传承'},
|
|
|
2: {'label': '梨园雅韵·表演', 'desc': '感受南京传统表演艺术的独特韵味与舞台魅力'},
|
|
|
3: {'label': '人间烟火·民俗', 'desc': '体验南京丰富多彩的民俗活动与民间传统'},
|
|
|
4: {'label': '口传心授·文学', 'desc': '领略南京口传文学的语言艺术与文化内涵'},
|
|
|
5: {'label': '匠心传承·人物', 'desc': '认识南京非物质文化遗产的传承人与守护者'},
|
|
|
}
|
|
|
|
|
|
# LXC: 根据分类ID获取对应的分类信息,如果不存在则使用默认值
|
|
|
category_info = category_map.get(category_id, {
|
|
|
'label': category.name,
|
|
|
'desc': f'探索南京{category.name}的独特魅力'
|
|
|
})
|
|
|
|
|
|
# LXC: 获取该分类下已发布的文章,按创建时间倒序排列
|
|
|
posts = Post.objects.filter(category=category, status='published').order_by('-created_time')
|
|
|
|
|
|
# LXC: 构建上下文数据
|
|
|
context = {
|
|
|
'post_list': posts,
|
|
|
'hot_posts': hot_posts,
|
|
|
'category_info': {
|
|
|
'name': category.name,
|
|
|
'label': category_info['label'],
|
|
|
'desc': category_info['desc']
|
|
|
},
|
|
|
'current_path': request.path,
|
|
|
'current_category_id': category_id
|
|
|
}
|
|
|
|
|
|
# LXC: 渲染分类页面模板并返回响应
|
|
|
return render(request, 'blog/index.html', context)
|
|
|
|
|
|
def detail(request, post_id):
|
|
|
"""文章详情页"""
|
|
|
# LXC: 根据文章ID获取已发布的文章对象,如果不存在则返回404
|
|
|
post = get_object_or_404(Post, id=post_id, status='published')
|
|
|
# LXC: 增加文章浏览量并保存到数据库
|
|
|
post.views += 1
|
|
|
post.save()
|
|
|
|
|
|
# LXC: 导入评论模型和表单
|
|
|
from comments.models import Comment
|
|
|
from comments.forms import CommentForm
|
|
|
|
|
|
# LXC: 获取该文章的所有评论,按创建时间倒序排列
|
|
|
comments = post.comments.all().order_by('-created_time')
|
|
|
# LXC: 创建评论表单实例
|
|
|
comment_form = CommentForm()
|
|
|
|
|
|
# LXC: 构建上下文数据
|
|
|
context = {
|
|
|
'post': post,
|
|
|
'comments': comments,
|
|
|
'comment_form': comment_form,
|
|
|
}
|
|
|
# LXC: 渲染文章详情页模板并返回响应
|
|
|
return render(request, 'blog/detail.html', context) |