56 lines
1.9 KiB
Python
56 lines
1.9 KiB
Python
from django.shortcuts import render, get_object_or_404
|
||
from .models import Post, Category
|
||
|
||
|
||
# Create your views here.
|
||
|
||
def index(request):
|
||
# 获取所有分类
|
||
categories = Category.objects.all()
|
||
|
||
# 获取查询参数中的分类ID
|
||
category_id = request.GET.get('category')
|
||
|
||
# 获取搜索关键词
|
||
query = request.GET.get('q')
|
||
|
||
# 获取搜索类型参数
|
||
search_type = request.GET.get('search_type', 'all')
|
||
|
||
# 根据分类和搜索关键词筛选文章
|
||
if query:
|
||
# 根据搜索类型执行不同的搜索
|
||
if search_type == 'title':
|
||
posts = Post.objects.filter(title__icontains=query)
|
||
elif search_type == 'content':
|
||
posts = Post.objects.filter(content__icontains=query)
|
||
else:
|
||
# 默认按标题和内容搜索
|
||
posts = Post.objects.filter(title__icontains=query) | Post.objects.filter(content__icontains=query)
|
||
elif category_id:
|
||
posts = Post.objects.filter(category_id=category_id)
|
||
else:
|
||
posts = Post.objects.all()
|
||
|
||
posts = posts.order_by('-publish_date').distinct()
|
||
|
||
# 为每篇文章添加摘要(前50个字符)
|
||
for post in posts:
|
||
# 移除HTML标签并截取前50个字符作为摘要
|
||
import re
|
||
clean_content = re.sub(r'<[^>]+>', '', post.get_markdown_content())
|
||
post.summary = clean_content[:50] + '...' if len(clean_content) > 50 else clean_content
|
||
|
||
return render(request, 'blog/index.html', {
|
||
'posts': posts,
|
||
'categories': categories,
|
||
'selected_category': category_id,
|
||
'query': query,
|
||
'search_type': search_type
|
||
})
|
||
|
||
|
||
def detail(request, post_id):
|
||
post = get_object_or_404(Post, pk=post_id)
|
||
categories = Category.objects.all() # 获取所有分类用于侧边栏
|
||
return render(request, 'blog/detail.html', {'post': post, 'categories': categories}) |