一个非常基本的问题,令我惊讶的是我找不到答案。我只是开始看django并进行了即装即用的安装。创建一个项目并创建一个应用程序。 urls.py的默认内容非常简单:
urlpatterns = [
path('admin/', admin.site.urls),
]
如果我打开django网站主页,则会获得带有火箭图片的内容。但是,就像我说的那样,我在项目中创建了另一个应用程序,我们称其为“ bboard ”。我在 bboard / views.py
中创建了一个简单的“ hello world”功能def index(request):
return HttpResponse('Hello world')
要使其能够通过浏览器访问,我已通过以下方式修改了原始的 urls.py 文件:
from bboard.views import index
urlpatterns = [
path('admin/', admin.site.urls),
path('bboard/', index),
]
通过这种方式,我可以访问 localhost:port / admin 和 localhost:port / bboard URL,但是如果我尝试使用 localhost打开主页:端口,现在出现找不到页面错误。
Django使用samplesite.urls中定义的URLconf,按以下顺序尝试了这些URL模式: 管理员/ 木板/ 空路径与任何这些都不匹配。
如果我注释掉urlpatterns列表中的第二项,则一切正常。那么,为什么附加模式会对此产生影响,并且需要采取哪些措施加以解决?
答案 0 :(得分:2)
您需要在根urls.py
中添加一个空url
urlpatterns = [
path('admin/', admin.site.urls),
path('', include(bboard.urls))
]
答案 1 :(得分:1)
在添加自己的路由之前,Django将在'/'网址处提供默认主页。添加自己的路由配置后,django不再提供其默认示例主页。
来自Django的django/views/debug.py
:
def technical_404_response(request, exception):
"""Create a technical 404 error response. `exception` is the Http404."""
try:
error_url = exception.args[0]['path']
except (IndexError, TypeError, KeyError):
error_url = request.path_info[1:] # Trim leading slash
try:
tried = exception.args[0]['tried']
except (IndexError, TypeError, KeyError):
tried = []
else:
if (not tried or ( # empty URLconf
request.path == '/' and
len(tried) == 1 and # default URLconf
len(tried[0]) == 1 and
getattr(tried[0][0], 'app_name', '') == getattr(tried[0][0], 'namespace', '') == 'admin'
)):
return default_urlconf(request)
请注意,如果包括的唯一URL路径是管理路径,而请求的URL是else
,则最后一个default_urlconf
块将返回/
。 default_urlconf
是您提到的样本Rocket页面。一旦添加了自己的任何路由,if
块中的else
语句将为false,因此不会返回default_urlconf
,而是进入常规404处理程序。>
这里是default_urlconf
def default_urlconf(request):
"""Create an empty URLconf 404 error response."""
with Path(CURRENT_DIR, 'templates', 'default_urlconf.html').open() as fh:
t = DEBUG_ENGINE.from_string(fh.read())
c = Context({
'version': get_docs_version(),
})
return HttpResponse(t.render(c), content_type='text/html')