Question

I have a django application hosted with Apache. I'm busy using the django restframework to create an API, but I am having issues with URLs. As an example, I have a URL like this:

url(r'path/to/endpoint/(?P<db_id>.+)/$', views.PathDetail.as_view())

If I try to access this url and don't include the trailing slash, it will not match. If I add a question mark on at the end like this:

url(r'path/to/endpoint/(?P<db_id>.+)/?', views.PathDetail.as_view())

This matches with and without a trailing slash. The only issue is that if a trailing slash is used, it now gets included in the db_id variable in my view. So when it searches the database, the id doesn't match. I don't want to have to go through all my views and remove trailing slashes from my url variables using string handling.

So my question is, what is the best way to make a url match both with and without a trailing slash without including that trailing slash in a parameter that gets sent to the view?

Was it helpful?

Solution

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.

OTHER TIPS

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>[^/]+)/?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top