Rainbow
Rainbow

Reputation: 85

Django - Redirecting from trailing slash to non-trailing slash

I like how Django redirects from /some/url to /some/url/ when I use regex ^/some/url/$, but it doesn't do vice versa, e.g. redirecting from /some/url/ to /some/url when I use regex ^/some/url$.

How could I add this feature from inside of my django app instead of using manual mod_rewrite?

Upvotes: 1

Views: 1036

Answers (1)

Rainbow
Rainbow

Reputation: 85

I've got it working. I've added /? to my URL RegEx, right before the $ sign at the end. Then I've added this to my views.py:

from django.shortcuts import redirect
# ...
def some_view(request, some_param):
    if request.path[-1] == '/':
        return redirect(request.path[:-1])
    # ...

Upvotes: 4

Related Questions