- Author:
- ubernostrum
- Posted:
- August 24, 2007
- Language:
- Python
- Version:
- .96
- Score:
- 5 (after 5 ratings)
When I initially set up my blog, I put together the archives with URL patterns like so:
/weblog/2007/
goes toarchive_year
/weblog/2007/08/
goes toarchive_month
/weblog/2007/08/24/
goes toarchive_day
/weblog/2007/08/24/some-slug
goes toobject_detail
The same patterns held for links, only the prefix was /links/
instead of /weblog/
.
For a forthcoming redesign/rewrite, I'm switching to using abbreviated month names (e.g., "aug", "sep", "oct", etc.) in the URLs, which means I need to redirect from the old-style URLs to the new. This snippet is the solution I hit upon. Two things are notable here:
- Each one of these views uses reverse(), called with the appropriate arguments, to generate the URL to redirect to. This means URLs don't have to be hard-coded in.
- Each view takes an argument --
object_type
-- which is used to generate the view name to pass toreverse
, meaning that only one set of redirect views had to be written to handle both entries and links.
This is just one of many handy tricks reverse
can do :)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | from django.core.urlresolvers import reverse
from django.http import HttpResponsePermanentRedirect
MONTH_DICT = { '01': 'jan',
'02': 'feb',
'03': 'mar',
'04': 'apr',
'05': 'may',
'06': 'jun',
'07': 'jul',
'08': 'aug',
'09': 'sep',
'10': 'oct',
'11': 'nov',
'12': 'dec' }
def redirect_detail(request, year, month, day, slug, object_type):
return HttpResponsePermanentRedirect(reverse('coltrane_%s_detail' % object_type,
kwargs={ 'year': year,
'month': MONTH_DICT[month],
'day': day,
'slug': slug }))
def redirect_archive_day(request, year, month, day, object_type):
return HttpResponsePermanentRedirect(reverse('coltrane_%s_archive_day' % object_type,
kwargs={ 'year': year,
'month': MONTH_DICT[month],
'day': day }))
def redirect_archive_month(request, year, month, object_type):
return HttpResponsePermanentRedirect(reverse('coltrane_%s_archive_month' % object_type,
kwargs={ 'year': year,
'month': MONTH_DICT[month] }))
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
I'd probably use HttpResponsePermanentRedirect instead of HttpResponseRedirect, if the new URLs are going to stick!
#
Good catch.
#
Please login first before commenting.