django教程:自定义404和500视图

编程入门 行业动态 更新时间:2024-10-11 03:15:53
本文介绍了django教程:自定义404和500视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

Windows 7 Python 2.7.3 Django 1.5 python manage.py runserver

Windows 7 Python 2.7.3 Django 1.5 python manage.py runserver

我正在按照位于' docs.djangoproject/en/1.5上的教程进行操作/intro/tutorial03/'

在事情变得混乱之前,我得到了写一个404(未找到页面)视图"的信息.

I got as far as the 'Write a 404 (page not found) view' before things got wierd.

我试图找出如何制作自定义404视图.但是,我不确定:

I have tried to work out how to make a custom 404 view. However, I am not sure:

A.自定义404.html文件应确切位于何处.它应该在我的项目目录树中还是在Django目录树中.我的项目目录树如下所示

A. Where exactly the custom 404.html file should reside. Should it be in my project directory tree or in my Django directory tree. My project directory tree looks like this,

1> mysite 2> - mysite 3> - polls 4> - templates 5> - polls 6> - templates 7> - admin

当前404.html是@ 6>

Currently the 404.html is @ 6>

B.必须在哪里进行哪些修改?我了解需要在"root" URL conf中设置handler404和handler500.我有一个驻留在@ 2>和3>的url.py(请参见上面的树).假设2>是正确的位置,我假定语法如下,

B. What modifications have to be made where? I understand that a handler404 and a handler500 need to be set in the 'root' url conf. I have a url.py residing @ 2> and 3> (see tree above). Assuming that 2> is the correct place I assume that the syntax is as follows,

handler404 = 'templates.404' handler500 = 'templates.500'

还有什么需要设置的,在哪里?

What else needs to be set, where?

推荐答案

据我所知,您有一个小错误,但请不要担心.

As I can see you have a little mistake, but dont worry.

看,试试这个:

handler404 = 'mysite.views.error404'

然后在mysite(第二个mysite)中创建一个views.py(如果没有).在该views.py文件中输入:

Then in mysite (the second mysite) creates a views.py if you dont have. In that views.py put:

from django.shortcuts import render def error404(request): return render(request,'404.html')

仅此而已!在模板中,创建该文件并执行一些操作!

and thats all! In templates, create that file and do something nice!

请记住,仅在生产版本(DEBUG=False)中有效,否则django使用回溯. 对于505也是一样,您也许可以尝试handler404 = 'polls.views.see404'并放入views.py中,但是您知道,口味是不同的.

Remember that only works in production (DEBUG=False) otherwise django use the traceback. Is the same for 505, and you maybe can try handler404 = 'polls.views.see404' and put in the views.py then but you know, tastes are different hehehe.

现在,尝试其他操作,例如:在urls.py中注释

Now, try something else, for example: comment in the urls.py

#handler404 = 'mysite.views.error404'

并在views.py中也删除.

and remove too in the views.py the def.

在模板文件的索引中创建一个简单的404.html. 在生产环境中运行服务器并产生404错误,发生了什么事?

In the index of your templates file creates a simple 404.html. Run the server in production and produce that 404 error, what happened?

更多推荐

django教程:自定义404和500视图

本文发布于:2023-11-02 06:00:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1551561.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   视图   教程   django

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!