[Django]-Django URLs – trailing slash gets added to variable value

5👍

Your pattern for the parameter is .+, which means 1 or more of any character, including /. No wonder the slash is included in it, why wouldn’t it?

If you want the pattern to include anything but /, use [^/]+ instead. If you want the pattern to include anything except slashes at the end, use .*[^/] for the pattern.

4👍

The .+ part of your regex will match one or more characters. This match is “greedy”, meaning it will match as many characters as it can.

Check out: http://www.regular-expressions.info/repeat.html.

In the first case, the / has to be there for the full pattern to match.

In the second case, when the slash is missing, the pattern will match anyway because the slash is optional.

If the slash is present, the greedy db_id field will expand to the end (including the slash) and the slash will not match anything, but the overall pattern will still match because the slash is optional.

Some easy solutions would be to make the db_id non greedy by using the ? modifier: (?P<db_id>.+?)/? or make the field not match any slashes: (?P<db_id>[^/]+)/?

Leave a comment