Skip to content

Instantly share code, notes, and snippets.

@trey
Created May 23, 2012 12:26
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trey/2774991 to your computer and use it in GitHub Desktop.
Save trey/2774991 to your computer and use it in GitHub Desktop.
Smart URL Redirects in Django

Smart URL Redirects in Django

While building ComicBinder's URLs, I wanted a way to differentiate a volume of a title other than one, and a printing of an issue other than one. So, for example, a URL to the second printing of the second volume of Amazing Spider-Man #1 would look like:

/marvel/amazing-spider-man_2/1_2/

That's easy enough with some URLconf wrangling. What I'm talking about today is automatically redirecting a request for _1 in any of those places to the same URL without the _1. While technically correct, I want the lack of underscore + number to mean one, and for there to be only one URL for a resource (someone send me a link to a clever article that talks about this).

django.views.generic.simple.redirect_to to the rescue. Try something like this:

(r'^(?P<publisher>[-\w]+)/(?P<title>[-\w]+)_1/(?P<number>\d+)_1/$', 'django.views.generic.simple.redirect_to', {'url': '/%(publisher)s/%(title)s/%(number)s/'}),

I made a few of these to account for situations where it was the first volume, but nothing specified for printing, and vise versa.

Not too bulky, and since I have that sitting near the normal rule, it shouldn't put me out too much to update it if I make any changes.

Source

@trey
Copy link
Author

trey commented May 23, 2012

@bolshoibooze
Copy link

For other folks stumbling upon this,it doesn't work from 1.5 onwards,use the class-based version of it:
url(r'^$', 'RedirectView.as_view(url='/name/of/ur/url')),

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment