django - 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.
我能做些什么来解决这个问题?
解决方案
您正在混合path
andre_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"),
推荐阅读
- unit-testing - 如何在基于现代目标的 cmake 中使用单元测试目标管理库的私有依赖项
- r - R 计算多年来每一天的趋势
- c# - 无法动态设置数组初始值设定项长度
- php - 在多维数组中查找特定值
- django - Django没有名为'static_root'的模块
- apache-kafka-streams - KafkaStream 不使用 Consumed.with() 中给出的 serde,而是使用默认的 serde
- nginx - 代理传递到外部服务器(NGINX 到 Azure 流量管理器)
- javascript - javascript 悬停一个元素并影响另一个元素
- php - 如何获取一些 API 信息并设置为变量
- google-api - 是否有其他人收到“服务暂时不可用”。来自 Google 图书 API?