Urlpatterns: category/subcategory/article-slug


Django==3.2.5
re_path(r'^.*/.*/<slug:slug>/$', Single.as_view(), name="single"),

在这里,我试图组织以下模式:类别/子类别/文章段塞。在这种情况下,类别和子类别没有标识任何内容。只有鼻涕虫才有意义。

现在我尝试:

http://localhost:8000/progr/django/1/

得到这个:

Page not found (404)
Request Method: GET
Request URL:    http://localhost:8000/progr/django/1/
Using the URLconf defined in articles_project.urls, Django tried these URL patterns, in this order:
admin/
^.*/.*/<slug:slug>/$ [name='single']
articles/
^static/(?P<path>.*)$
^media/(?P<path>.*)$
The current path, progr/django/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.

我能做些什么来解决这个问题?

您混合了pathre_path函数,re_path没有路径转换器,只使用regex,因此,当您编写<slug:slug>时,它的字面意思是url中有精确的字符串,而您希望捕获模式[-a-zA-Z0-9_]+(这是Django用于slug的模式(。此外,在您的模式中使用.*可能会给您带来问题,因为它也可能与/匹配,并可能导致您的一些其他URL永远不会被使用,相反,您可能希望使用[^/]*。所以你可能想把你的模式改为:

re_path(r'^[^/]*/[^/]*/(?P<slug>[-a-zA-Z0-9_]+)/$', Single.as_view(), name="single"),

这对我来说仍然有点问题,因为它匹配了两个任意的模式,并且没有捕获并将它们传递给视图,事实上,你可能只想改用path并捕获这些模式:

from django.urls import path

path('<str:some_string1>/<str:some_string2>/<slug:slug>/', Single.as_view(), name="single"),

最新更新