Top / Programming / Python / Django TIPS / 他のURLへリダイレクトする

他のURLへリダイレクトする

他のURLへリダイレクトする方法を解説します。

urls.pyで汎用ビューを使用する方法と、views.pyでHttpResponseRedirectやHttpResponsePermanentRedirectを使用する方法があります。

汎用ビューを使用する方法

汎用ビューのdjango.views.generic.simple.redirect_toを使用することで、指定の URL へリダイレクトすることができます。

project/
├__init__.py
├manage.py
├settins.py
├urls.py <-このファイルを編集する
└application/
  ├__init__.py
  ├models.py
  └views.py

以下の例では、/old/を/new/にリダイレクトします。

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

以下の例では、/old/<id>/を/new/<id>/にリダイレクトします。

urlpatterns = patterns('',
    ('^old/(?P<id>\d+)/$', 'django.views.generic.simple.redirect_to', {'url' : '/new/%(id)s/'}),
)

以下の例では、 /bar/ へのリクエストに対して HTTP 410 エラーを返します:

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

HttpResponseRedirectを使用する方法

HttpResponseRedirect はリダイレクト先のURLを引数にとります。
HTTP状態コード302を返します。

project/
├__init__.py
├manage.py
├settins.py
├urls.py
└application/
  ├__init__.py
  ├models.py
  └views.py <-このファイルを編集する

以下の例では、/bbs/2/にリダイレクトします。

def index(request):
    return HttpResponseRedirect("/bbs/2/")

以下の例では、http://www.yahoo.co.jp/にリダイレクトします。

def index(request):
    return HttpResponseRedirect("http://www.yahoo.co.jp/")

HttpResponsePermanentRedirectを使用する方法

HttpResponsePermanentRedirectの使い方はHttpResponseRedirectと同じです。

HTTP状態コードがHttpResponseRedirectと異なり、永続リダイレクト(HTTP状態コード301)を使います。

外部リンク

更新履歴