2

I'm trying to get '/' to redirect to '/first-page' where '/first-page' is a built-in flat page with the slug first-page

I'm looking for something like

(r'^/', 'redirect_to', {'url': '/flat-page'}),
Marc Condon
  • 397
  • 4
  • 12
  • possible duplicate of [Python + Django page redirect](http://stackoverflow.com/questions/523356/python-django-page-redirect) – Josh Lee Dec 15 '10 at 23:57
  • @jleedev: it is a duplicate, but the "best" answer has changed since then with the introduction of the `redirect_to` generic view. – Chris Morgan Dec 16 '10 at 00:20
  • @Chris, `redirect_to` was in Django 1.0 (http://docs.djangoproject.com/en/1.0/ref/generic-views/#django-views-generic-simple-redirect-to) which existed before that top voted answer on the possible duplicate. Tssk. Let's upvote the `redirect_to` answer over there to fix this travesty http://stackoverflow.com/questions/523356/python-django-page-redirect/3841632#3841632 ;) – Day Dec 16 '10 at 00:32
  • @Day: not checking my sources again... *sigh* :-) – Chris Morgan Dec 16 '10 at 01:22

3 Answers3

3

Use Django's generic views

urlpatterns = patterns('django.views.generic.simple',
    ('^$', 'redirect_to', {'url': '/first-page'}),
)
urlpatterns += patterns('myProject.myApp',
    ...
)

or

urlpatterns = patterns('',
    ('^$', 'django.views.generic.simple.redirect_to', {'url': '/first-page'}),
    ...
)

See the docs for more info and examples.

Watch your URL matching too, that one you have will match anything starting with /. Like example.com//anything, note the double slash.

Wladimir Palant
  • 56,865
  • 12
  • 98
  • 126
Jake
  • 12,713
  • 18
  • 66
  • 96
  • +1 for `django.views.generic.simple.redirect_to`, +1 for `'^$'` instead of `'^/'` which will match everything and so would need to go last and would break 404s. – Chris Morgan Dec 16 '10 at 00:18
  • Thanks @Chris, am I right that `r'^/'` would match `example.com//anything` but not `example.com/anything` ? I haven't tested that. -- Update: tested and correct. – Jake Dec 16 '10 at 00:22
1

Inside the view for the url, you can use HttpResponseRedirect.

from django.http import HttpResponseRedirect

def rootview(request):
    return HttpResponseRedirect('/flat-page')
TheNone
  • 5,684
  • 13
  • 57
  • 98
dheerosaur
  • 14,736
  • 6
  • 30
  • 31
1

Use HttpResponsePermanentRedirect:

from django.http import HttpResponsePermanentRedirect
# ...
(r'^$', 'redirect_to', lambda request: HttpResponsePermanentRedirect('/flat-page')),
aligf
  • 2,020
  • 4
  • 19
  • 33
  • 1
    I don't think that will even work. If you insist on using a lambda function do this: `(r'^$', lambda request: HttpResponsePermanentRedirect('/flat-page'))` – Jake Dec 16 '10 at 00:18
  • You're right. I took the code from the question, which I assumed to be correct. – aligf Dec 16 '10 at 00:23