Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/blog/about/ Raised by: b

错误:

Page not found (404)
Request Method: GET
Request URL:    http://127.0.0.1:8000/blog/about/
Raised by:  blog.views.about
No BlogPost matches the given query.

解决措施:

def projects(request):
    # use markdown to show projects
    the_projects_post = get_object_or_404(BlogPost, title="projects")
    args = {"projects": the_projects_post}
    return render(request, 'blog/projects.html', args)

当我把代码改成这样时,

def projects(request):
    # # use markdown to show projects
    # the_projects_post = get_object_or_404(BlogPost, title="projects")
    # args = {"projects": the_projects_post}
    # return render(request, 'blog/projects.html', args)
    return HttpResponse('这个页面我也还没写')

It works! 原因就在于,我数据库里还没有名为projects的章,所以,返回404 页面。

get_object_or_404()是个什么玩意儿?Django官方文档之快捷函数
快捷函数是什么呢?快捷函数顾名思义就是用起来很方便,很快捷。
接着,来说下他的用法。

get_object_or_404(klass, *args, **kwargs)
Calls get() on agiven model manager, but it raises Http404 instead of the model’sDoesNotExist exception.

Required arguments

klass A Model class, a Manager, or a QuerySet instance from which to get the object.
**kwargs Lookup parameters, which should be in the format accepted by get() and filter().

get_object_or_404()更有意思的地方在它和try….except…语句等价,所以这就不得了了。省事的不是一点两点。下面我先贴出自己的代码改成try…except..形式。如果运行结果和之前的一样。那我们就能说这俩等价了。

def projects(request):
    # # use markdown to show projects
    # the_projects_post = get_object_or_404(BlogPost, title="projects")
    # args = {"projects": the_projects_post}
    # return render(request, 'blog/projects.html', args)
    try:
        the_projects_post = BlogPost.objects.get(title='projects')
        args = {"projects": the_projects_post}
        return render(request, 'blog/projects.html', args)
    except BlogPost.DoesNotExist:
        return HttpResponse('页面没有找到')

Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/blog/about/ Raised by: b_第1张图片
所以,看结果,get_object_or_404()和try…except…是等价的。当try中出错后,就直接执行except语句块。所以自然也就看不到‘blog/projects.html’这个页面了。

你可能感兴趣的:(Djngo/Django部署)