""" 视图函数 每个函数对应一个页面 接收 HTTP 请求,返回 HTTP 响应 """ from django.shortcuts import render, get_object_or_404 from .models import Post def post_list(request): """ 文章列表页 逻辑: 1. 从数据库查询所有已发布的文章 2. 按发布时间倒序排列(模型 Meta 里已定义 ordering) 3. 把数据传给模板渲染 """ # filter(status='published') 只取已发布的 # 草稿不会出现在前台 posts = Post.objects.filter(status='published') # render 函数:加载模板 + 传入上下文数据 + 返回 HttpResponse return render( request, # HTTP 请求对象 'blog/post_list.html', # 模板路径 {'posts': posts} # 传给模板的数据(上下文) ) def post_detail(request, slug): """ 文章详情页 参数: slug: URL 里的文章别名,比如 /hello-world/ 里的 hello-world 逻辑: 1. 根据 slug 查找文章 2. 找不到就返回 404 3. 找到就渲染详情模板 """ # get_object_or_404:查到了返回对象,查不到直接抛 404 post = get_object_or_404( Post, # 模型类 slug=slug, # 查找条件:slug 匹配 status='published' # 且状态是已发布 ) return render( request, 'blog/post_detail.html', {'post': post} )