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?

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
    # …
Вернуться на верх