Задать вопрос

Тел: +7 965 3737 888

481

Просмотров

2

Ответов

Using reverse() to do redirects

<p>When I initially set up my blog, I put together the archives with URL patterns like so:</p>
<ul><li>/weblog/2007/ goes to archive_year</li>
<li>/weblog/2007/08/ goes to archive_month</li>
<li>/weblog/2007/08/24/ goes to archive_day</li>
<li>/weblog/2007/08/24/some-slug goes to object_detail</li>
</ul><p>The same patterns held for links, only the prefix was /links/ instead of /weblog/.</p>
<p>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:</p>
<ol><li>Each one of these views uses <a href="http://www.djangoproject.com/documentation/url_dispatch/#reverse">reverse()</a>, called with the appropriate arguments, to generate the URL to redirect to. This means URLs don't have to be hard-coded in.</li>
<li>Each view takes an argument -- object_type -- which is used to generate the view name to pass to reverse, meaning that only one set of redirect views had to be written to handle both entries and links.</li>
</ol><p>This is just one of many handy tricks reverse can do :)</p>

Вопрос полезен? Да0/Нет0
file_2385.py(1.6Кб)
None

Ответы (2):

Ответubernostrum:25.08.2007
Ответ полезен? Да0/Нет0

Good catch.

Ответmbi:25.08.2007
Ответ полезен? Да0/Нет0

I'd probably use HttpResponsePermanentRedirect instead of HttpResponseRedirect, if the new URLs are going to stick!