在制作网页过程中,网站需要格式各样的验证。比如百度站长、搜狗联盟的校验网站。不止如此,有时写一个静态页面,也没有必要再去搞一个路由出来。这个时候,想到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 ]
在urls.py文件当中写入如下逻辑
1 from django.conf import urls 2 from .views import page_not_found 3 urls.handler404 = page_not_found
在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')