Django网站制作根目录,巧用404,可访问根目录任意网页

原文链接:http://www.bianbingdang.com/article_detail/106.html

在制作网页过程中,网站需要格式各样的验证。比如百度站长、搜狗联盟的校验网站。不止如此,有时写一个静态页面,也没有必要再去搞一个路由出来。这个时候,想到Django的404页面的定义,所有的不存在的页面会被定向到404页面,那么就在这块加点逻辑。首先,再setting配置文件得到自己的根目录,我定义根目录在网站之下的root目录

1 TEMPLATES = [
2     {
3         'BACKEND': 'django.template.backends.django.DjangoTemplates',
4         'DIRS': [os.path.join(BASE_DIR, 'bianbingdang/root'),]
5 ]
View Code

在urls.py文件当中写入如下逻辑

1 from django.conf import urls
2 from .views import page_not_found
3 urls.handler404 = page_not_found
View Code

在views.py定义逻辑如下,也就是说,当发现root目录下存在请求的文件时,就向浏览器返回该页面:

 1 import os
 2 from django.shortcuts import render_to_response
 3 from .settings import TEMPLATES
 4 def page_not_found(request, **kwargs):
 5     root_templates = os.listdir(TEMPLATES[0]['DIRS'][-1])
 6     print(request.path[1:] in root_templates)
 7     if request.path[1:] in root_templates:
 8         print(request.path)
 9         return render_to_response(request.path[1:])
10     return render_to_response('error/404.html')
View Code

 

posted @ 2018-12-18 20:55  白水乡巴佬  阅读(926)  评论(0编辑  收藏  举报