python - 路径不匹配
问题描述
我已经开始学习 Django,我正在观看这个讲座(直到开始 20 分钟)并按照说明进行操作,但我得到的错误是:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/hello
Using the URLconf defined in lecture3.urls, Django tried these URL patterns, in this order:
admin/
The current path, hello, didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file.
Change that to False, and Django will display a standard 404 page.
运行后
python3 manage.py runserver
我在“lecture3”应用程序中的 settings.py 文件是:
# Application definition
INSTALLED_APPS = [
'hello',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
以及其他一些内容。
“hello”应用程序中的views.py文件是:
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
def index(request):
return HttpResponse("Hello World!")
“hello”应用程序中的 urls.py 文件是:
from django.urls import path
from . import views
urlpatterns=[
path("",views.index, name="index")
]
“lecture3”应用程序中的 urls.py 文件是:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('/hello/', include('hello.urls'))
]
我在这里检查了类似的问题,但我的问题没有解决。谁能告诉我为什么会收到此错误。任何帮助,将不胜感激。
解决方案
鉴于:
...
path('/hello/', include('hello.urls'))
...
从路径中删除第一个斜杠:
...
path('hello/', include('hello.urls'))
...
然后您需要使用尾部斜杠访问它,/
如下所示http://127.0.0.1:8000/hello/
或者使用 Django 的约定,APPEND_SLASH=True
在你的settings.py
so 访问中使用http://127.0.0.1:8000/hello
将重定向到http://127.0.0.1:8000/hello/