Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass arguments with slash in Django2 urls

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

like image 549
Henry Henrinson Avatar asked Mar 31 '18 11:03

Henry Henrinson


People also ask

How do I pass parameters via URL in Django?

Django URL pass parameter to view You can pass a URL parameter from the URL to a view using a path converter. Then “products” will be the URL endpoint. A path converter defines which type of data will a parameter store. You can compare path converters with data types.

How can we handle URLs in Django?

Django provides tools for performing URL reversing that match the different layers where URLs are needed: In templates: Using the url template tag. In Python code: Using the reverse() function. In higher level code related to handling of URLs of Django model instances: The get_absolute_url() method.

What is append slash in Django?

Among Django's many built-in features is APPEND_SLASH, which by default is set to True and automatically appends a slash / to URLs that would otherwise 404. Note: Web browsers aggressively cache past URLs and will often automatically add a trailing slash / as a result.

What happens if you skip trailing slash in Django?

The local Django webserver will automatically restart to reflect the changes. Try again to refresh the web page for the User section of the admin without the trailing slash: 127.0. 0.1:8000/admin/auth/user .


1 Answers

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

Use <path:test_arg> to match forward slashes.

like image 160
Alasdair Avatar answered Oct 05 '22 01:10

Alasdair