django-Views之常见的几种错误视图代码(三)

时间:2022-07-23
本文章向大家介绍django-Views之常见的几种错误视图代码(三),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1.404 page not found(找不到对应的页面)

2.500 server error(服务器错误)

3.400 bad request(无效的请求)

4.403 HTTP forbidden(HTTP禁止访问,权限不足)

5.200 OK (请求成功)

重新定义404模板: book/urls.py

from django.urls import path
from . import views
from django.conf.urls import handler404
app_name ="book"
urlpatterns = [
    path('',views.index,name="index"),
]
handler404=views.page_not_found

book/views.py

from django.http import HttpResponse
from django.shortcuts import render,redirect,reverse
from django.urls import resolve

# Create your views here.
def index(request):
    return HttpResponse("welcome")
def page_not_found(request,exception=404):
    return render(request,template_name="404.html")

settings.py

DEBUG = False

ALLOWED_HOSTS = ["*"]

404.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>好像出了点问题,界面消失了</h1>
</body>
</html>