如何在 Django url 中使用斜杠传递参数

How to pass arguments with slash in Django2 urls

我想用包含正斜杠的参数调用 Django URL。例如,我想用 'test1/test2' 调用 mysite.com/test/。 (例如天真地,url 将是 mysite.com/test/test1/test2

urls.py:

urlpatterns = [
    path('test/<test_arg>/', views.test, name='test'),
]

访问以下任一失败:

  1. mysite.com/test/test1/test2
  2. mysite.com/test/test1%2Ftest2(%2F 是正斜杠的标准 URL 编码)

出现以下错误:

错误:

Using the URLconf defined in test.urls, Django tried these URL patterns, in this order:

    reader/ test/<test_arg>/
    admin/

The current path, test/test1/test2/, didn't match any of these.

我预计使用 1 中的路径会失败,但令我惊讶的是 2 中的路径会失败。

正确的做法是什么?

使用 Django 2.0.2

默认path converter <test_arg>(相当于<str:test_arg>)不匹配正斜杠。

使用 <path:test_arg> 匹配正斜杠。