13

I would like to call a Django URL with an argument containing a forward slash. For example, I would like to call mysite.com/test/ with 'test1/test2'. (e.g. naively, the url would be mysite.com/test/test1/test2)

urls.py:

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

Accessing either of the following fails:

  1. mysite.com/test/test1/test2
  2. mysite.com/test/test1%2Ftest2 (%2F is the standard URL encoding for forward slash)

with the below error:

Error:

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.

I would expect using the path in 1 to fail, but I am surprised the path in 2 fails.

What is the correct way of going about this?

Using Django 2.0.2

Henry Henrinson
  • 5,203
  • 7
  • 44
  • 76

1 Answers1

23

The default path converter <test_arg> (equivalent to <str:test_arg>) does not match forward slashes.

Use <path:test_arg> to match forward slashes.

Alasdair
  • 298,606
  • 55
  • 578
  • 516