Django 关于404页面的设定

使用注意:

1.url路由一个都不匹配会触发,或者在你的视图中触发Http404的错误。
2.如果DEBUG设置为True,则将永远不会使用404视图,而将显示URLconf以及一些调试信息。

from django.http import Http404


def pages(request, *age, **kwargs):
    page = kwargs.get("id", None)
    if not page:
        return render(request, "404.html")
    try:
        result = models.PageModel.objects.get(id=int(page))
    except:
        raise Http404()      #注意:这里不是return  是raise
    return render(request, "page.html",{"result":result})

在templates文件夹下新增一个404.html命名的页面,django会自动访问

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>404</title>
</head>
<body>
    <h1>404</h1>
</body>
</html>

参考链接:
https://docs.djangoproject.com/en/3.1/ref/views/#the-404-page-not-found-view
https://docs.djangoproject.com/en/3.1/topics/http/views/#django.http.Http404

posted @ 2020-12-22 14:55  lisicn  阅读(360)  评论(0编辑  收藏  举报