Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django is adding slash into dynamic URL segment

I have a dynamic url configured like so:

path('segment/', func1, name='func1'),
path('segment/<str:string>/', string, name='string'),

However, when I go to https://example.com/segment/watch?v=nTeq0U_V15U (watch?v=nTeq0U_V15U being the string), a slash is automatically added in middle, making it https://example.com/segment/watch/?v=nTeq0U_V15U/. Interestingly enough that does not throw a 404 error even though I have no URL pattern with 3 segments in urls.py. However, my question is why is the slash being added in, and how can I avoid it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

However, my question is why is the slash being added in, and how can I avoid it?

Because of the APPEND_SLASH setting [Django-doc], which is by default set to True.

This will, when no match is found for a given path, and the path does not end with a slash, do a redirect to the path with a slash, so the browser will try to fetch the page ending with a slash.

But the question shows some misunderstanding. Indeed, if you write:

https://example.com/segment/watch?v=nTeq0U_V15U
       \___ ______/\______ _____/\_____ ______/
           v              v            v
        hostname        path       querydict

then ?v=nTeq0U_V15U is not part of the path, it is part of the querydict, so it will not match <str:string>, only watch will.

You thus retrieve that in your view as:

def string(request, string):
    # string will be 'watch'
    print(request.GET['v'])  # nTeq0U_V15U
    # …
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading