我刚刚设置了 django 环境,正如教程所说。我打字python manager.py runserver,它告诉我打开127.0.0.1:8000。当我打开它时,它与正确的欢迎页面一起工作。
但这是我的问题:谁生成了这个默认的欢迎页面?由于没有views.py并且urls.py页面是空的。
如果您urls.py是空的(因为不包含匹配 url 的模式)并且 Django 处于调试模式(DEBUG = True在您的设置中),那么 Django 会触发您看到的页面。
Django 视图:
https://github.com/django/django/blob/main/django/views/debug.py#L575-L583
HTML模板:
如果有人想取回它(或重新使用它),您只需要将debug.default_urlconf视图添加到您的urls:
…
from django.views import debug
…
urlpatterns = [
…
path('', debug.default_urlconf),
…
]
Run Code Online (Sandbox Code Playgroud)
(免责声明:我使用的 django 版本:3.2.5,在旧版本中,文件内容可能会有所不同)
第一次运行 django Web 应用程序时看到的默认登录页面是“ default_urlconf.html ”。这是 django 添加的一种安全机制,而不是在没有任何默认 url/路由的情况下给出 404 错误。
django-admin startproject <project_name>当您第一次使用类似命令或使用任何 IDE 菜单控件(如“Pycharm professional”)创建 django 网站时,您将获得以下文件夹结构。DEBUG = True此外,在您的setting.py 文件中将“调试”设置为 True ( )
此外,当未设置路由或 url.py 中的 url 映射为空时,django 框架通过其错误处理代码提供默认路由。就像当您尝试访问/请求http://127.0.0.1:8000/时,django 会检查该 url 是否存在(404)以及调试模式是否处于活动状态。该请求会遍历各种 *.py 文件,如base.py、handlers.py、exceptions.py、 最后到达debug.py. 所有这些文件都是在虚拟环境中或在您(在项目中安装 django)时提供的。
最终,从“exception.py”通过方法转到“debug.py”**debug.technical_404_response(request, exc)**
def response_for_exception(request, exc):
if isinstance(exc, Http404):
if settings.DEBUG:
response = debug.technical_404_response(request, exc)
else:
response = get_exception_response(request, get_resolver(get_urlconf()), 404, exc)
Run Code Online (Sandbox Code Playgroud)
最后它感觉到debug.py有def technical_404_response(request, exception)哪个调用,最终它返回您在屏幕上看到的默认 html 页面( default_urlconf.htmldef default_urlconf(request) )的响应
def default_urlconf(request):
"""Create an empty URLconf 404 error response."""
with Path(CURRENT_DIR, 'templates', 'default_urlconf.html').open(encoding='utf-8') as fh:
t = DEBUG_ENGINE.from_string(fh.read())
c = Context({
'version': get_docs_version(),
})
return HttpResponse(t.render(c), content_type='text/html')
Run Code Online (Sandbox Code Playgroud)
文件位置:
异常.py:venv/Lib/site-packages/django/core/handlers/exception.py
debug.py: venv/Lib/site-packages/django/views/debug.py
default_urlconf.html : venv/Lib/site-packages/django/views/templates/default_urlconf.html
看看django/core/handlers/base.py和django/views/debug.py。简而言之,如果 django 收到 404 错误(如果您没有设置任何路由,则会出现 404 错误),然后在 base.py 中
if settings.DEBUG:
from django.views import debug
response = debug.technical_404_response(request, e)
Run Code Online (Sandbox Code Playgroud)
在 debug.py 中查看technical_404_response和empty_urlconf
| 归档时间: |
|
| 查看次数: |
1848 次 |
| 最近记录: |