Django3.2自定义404腾讯公益页面

记录下Django3.2版本如何自定义404腾讯公益页面

前言

  • 项目名称:project
  • 应用名称:app
  • settings.py 需设置 DEBUG = False 才生效

下面出现的 projectapp 需换成自己的

步骤

创建404.html

创建一个 ./app/templates/app/400.html 文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
<!DOCTYPE html>
<html lang="zh-CN">

<head>
<meta charset="UTF-8">
<title>404 Not Found</title>

<script type="text/javascript" src="//qzonestyle.gtimg.cn/qzone/hybrid/app/404/search_children.js" charset="utf-8"
homePageUrl="https://www.gaoyuanqi.cn" homePageName="回到我的主页">
</script>
</head>

</html>

该 html 有两处需要更改:

  • homePageUrl:跳转的网站域名
  • homePageName:跳转的链接文本

创建视图函数

./app/views.py 文件中添加:

1
2
3
4
5
from django.shortcuts import render

def page_not_found(request, exception):
# 404错误网址页面
return render(request, 'app/404.html', status=404)

添加全局路由

./project/urls.py 文件末尾添加:

1
handler404 = 'app.views.page_not_found'

handler404:固定写法,其值是视图函数路径

效果图

访问一个不存在的路径:
django-handler404