django html页面 404,django入门12:django 404与500错误跳转页面配置
时间: 2023-07-27 11:32:56 浏览: 49
对于Django中的404错误和500错误,我们可以通过配置来跳转到指定的错误页面。
首先,在项目的根目录下创建一个名为`templates`的文件夹,在该文件夹下创建一个名为`404.html`的文件,用于显示404错误页面。
接下来,在项目的`urls.py`中添加如下配置:
```
handler404 = 'myapp.views.page_not_found'
handler500 = 'myapp.views.server_error'
```
其中,`myapp.views.page_not_found`和`myapp.views.server_error`是我们自己定义的视图函数,用于处理404错误和500错误。
在`myapp/views.py`中定义这两个视图函数:
```
from django.shortcuts import render
def page_not_found(request, exception):
return render(request, '404.html', status=404)
def server_error(request):
return render(request, '500.html', status=500)
```
其中,`page_not_found`函数接收一个`exception`参数,表示捕获的异常信息。
最后,在`settings.py`中添加如下配置:
```
DEBUG = False
ALLOWED_HOSTS = ['yourdomain.com']
ADMINS = [('Your Name', 'your@email.com')]
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler',
'include_html': True,
},
},
'loggers': {
'django': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
},
}
```
其中,`DEBUG`设置为`False`表示关闭调试模式,`ALLOWED_HOSTS`设置允许访问的域名,`ADMINS`设置管理员邮箱,`LOGGING`设置日志记录方式。
这样,当出现404或500错误时,就会跳转到我们自定义的错误页面。