Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/blog/about/ Raised by: b
阿新 • • 發佈:2019-02-10
錯誤:
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('頁面沒有找到')
所以,看結果,get_object_or_404()和try…except…是等價的。當try中出錯後,就直接執行except語句塊。所以自然也就看不到‘blog/projects.html’這個頁面了。