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:
mysite.com/test/test1/test2
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
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.
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.
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.
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 .
The default path converter <test_arg>
(equivalent to <str:test_arg>
) does not match forward slashes.
Use <path:test_arg>
to match forward slashes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With