1

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?

Rainbow
  • 85
  • 1
  • 8
  • Don't. ULRs should end in slashes, if they don't refer to actual files. – Daniel Roseman Aug 04 '11 at 10:37
  • 1
    @Daniel I'd rather see trailing slash when a page is a list or 'folder' of articles and no trailing slash when a page is a single article. E.g. `/category/` for list of articles and `/category/article-title` for single article. It gives users info about what type of page they can expect. – Rainbow Aug 04 '11 at 11:30
  • possible duplicate of [django urls without a trailing slash do not redirect](http://stackoverflow.com/questions/1596552/django-urls-without-a-trailing-slash-do-not-redirect) – Wtower Feb 13 '15 at 10:48

1 Answers1

4

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])
    # ...
Kemal Fadillah
  • 9,760
  • 3
  • 45
  • 63
Rainbow
  • 85
  • 1
  • 8