如何忽略参数中 django URL 的正斜杠

how to ignore forward slash from django URL in a parameter

我使用的是 django 2.2.5 版。下面是我的urls.py

from django.urls import path, include
from . import views

urlpatterns = [
   path('manifest/', views.home),
   path('manifest/<str:some_id>/', views.manifest),
]

当 some_id 不包含任何正斜杠 (/) 时,它工作正常。例如。 http://127.0.0.1:8000/manifest/name:19.2.4:develop:1/

在 views.py 的以下清单函数中,我能够获得 some_id

def manifest(request, some_id):
     print(some_id)

##prints below:
##[21/Oct/2019 19:36:55] "GET /manifest/name:19.2.4:develop:1 HTTP/1.1" 301 0
##name:19.2.4:develop:1

但是,当 some_id 中包含正斜杠时,我无法获得完整的 ID。例如,从上面的 URL 如果我将 "develop" 替换为 "release/19.2.4" http://127.0.0.1:8000/manifest/name:19.2.4:release/19.2.4:1/

"GET /manifest/name:19.2.4:release/19.2.4:1/ HTTP/1.1" 404 3080

这是因为正斜杠被用作分隔符。有什么办法可以忽略 some_id 参数中的正斜杠吗?期望得到 name:19.2.4:release/19.2.4:1 作为 some_id 在 views.py

注意:有效 some_id 的格式是由“:”分隔的 4 个部分。例如:name:version:branch:num,其中只有分支部分可以有一个或多个斜杠 (/)。

你可能想要使用好的 ol' re_path 在你的情况下,这将给

from django.urls import path, re_path, include
from . import views

urlpatterns = [
   path('manifest/', views.home),
   re_path(r'manifest/(?P<some_id>\w+)/', views.manifest),
]

虽然你的 URL 是结构化的,但你是否尝试过类似的东西:

path('manifest/<str:name>:<str:version>:<path:branch>:<str:num>/', views.manifest),