包含在 urlpatterns 和 404 中

Include in urlpatterns and 404

我正在使用 Django 3.0.6

post/urls.py

from django.urls import path
from .views import PostDetailView


urlpatterns = [
    path('<int:pk>', PostDetailView.as_view(), name='detail'),
]

项目的urls.py

urlpatterns = []

if DEBUG:
    import debug_toolbar
    urlpatterns = [
        path('__debug__/', include(debug_toolbar.urls)),
    ]
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

urlpatterns += [
    path('', HomeView.as_view(), name='home'),
    path('{}'.format("admin/" if DEBUG else "dhjfsljdasdhje32/"), admin.site.urls), # Change admin url for security reasons.
    path('post/', include('post.urls')),
]

URL 在浏览器中

http://localhost:8000/post/1/

结果

Page not found (404)
Request Method: GET
Request URL:    http://localhost:8000/post/1/
Using the URLconf defined in pcask.urls, Django tried these URL patterns, in this order:

__debug__/
^media\/(?P<path>.*)$
[name='home']
admin/
post/ <int:pk> [name='detail']
The current path, post/1/, 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.

我该如何解决这个问题?

您的网址配置中缺少 尾部斜杠。所以,改变你的 post/urls.py

urlpatterns = [
    path(<b>'<int:pk>/'</b>, PostDetailView.as_view(), name='detail'),
                #^^^ trailing slash
]

然后尝试 /post/1/