首页 > 解决方案 > Urlpatterns:类别/子类别/文章-slug

问题描述

Django==3.2.5

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

在这里,我试图组织以下模式:类别/子类别/文章-slug。在这种情况下,类别和子类别无法识别任何内容。只有蛞蝓是有意义的。

现在我尝试:

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.

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

标签: django

解决方案


您正在混合pathandre_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"),

推荐阅读