博客五部曲之一 - 简单博客


1167 浏览 5 years, 3 months

17 获取实例条目或404

版权声明: 转载请注明出处 http://www.codingsoho.com/

可以用get_object_or_404函数来获取对象条目,如果查找内容不存在或返回多个,都会报错404.

下面例子中,在Post里面查找title为”title”的对象,并将返回的对象传递给模板。当然,我们有可以用id或者其他的字段来查询。

from django.shortcuts import render, get_object_or_404

def post_detail(request):
    instance = get_object_or_404(Post, title="title")
    context = {
        "title" : instance.title,
        "instance" : instance
    }
    return render(request, "post_detail.html",context)   

添加新模板post_detail.html,这个模板渲染detail视图。

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <h1>{{instance}}</h1>
    {{instance.title}}<br>
    {{instance.id}}<br>
</body>
</html>