Django URL 模式不起作用
Django URL pattern doesn't work
我的 urls.py
包括在内:
urlpatterns = [
path('files/', include('files.urls')),
]
然后,在 files/urls.py
中,我把这个:
urlpatterns = [
path('', views.index, name='index'),
path(r'(?P<name>[a-z]+)', views.check, name='check')
]
所以,我假设当 example.com/files
起作用时,example.com/files/somename
也应该起作用,但它不起作用:
Using the URLconf defined in example.urls, Django tried these URL
patterns, in this order:
[name='index']
files/ [name='index']
files/ (?P<name>[a-z]+) [name='check']
The current path, files/somename, didn't match any of these.
我在这里错过了什么?
您不需要在 path
方法中使用正则表达式。相反,您可以简单地将 str
指定为参数类型:
path('<str:name>/', views.check, name='check')
如果要使用正则表达式,请使用re_path
:
re_path(r'(?P<name>[a-z]+)', views.check, name='check')
我的 urls.py
包括在内:
urlpatterns = [
path('files/', include('files.urls')),
]
然后,在 files/urls.py
中,我把这个:
urlpatterns = [
path('', views.index, name='index'),
path(r'(?P<name>[a-z]+)', views.check, name='check')
]
所以,我假设当 example.com/files
起作用时,example.com/files/somename
也应该起作用,但它不起作用:
Using the URLconf defined in example.urls, Django tried these URL patterns, in this order:
[name='index'] files/ [name='index'] files/ (?P<name>[a-z]+) [name='check']
The current path, files/somename, didn't match any of these.
我在这里错过了什么?
您不需要在 path
方法中使用正则表达式。相反,您可以简单地将 str
指定为参数类型:
path('<str:name>/', views.check, name='check')
如果要使用正则表达式,请使用re_path
:
re_path(r'(?P<name>[a-z]+)', views.check, name='check')