概要
ビュー関数/ビュークラスのメソッドはHttpResponseクラスやその派生クラスのインスタンスを戻り値として、テンプレートをレンダリングしたり指定したURLに遷移する。
この戻り値の与え方としては、HttpResponseやその派生クラスのインスタンスを直接与える方法と、django.shortcutsで定義された関数(render、 redirect)を使う方法がある。
HttpResponseはレスポンスボディ―を指定して表示。ショートカットのrenderは引数にテンプレートファイルを指定し、それを表示する。
URLを指定したリダイレクトには、HttpResponseRedirectやショートカットのrenderを使う。
レンダリング
HttpResponse
HttpResponseはdjango.httpパッケージのモジュールで、ヘッダーや内容などを持つHTTPレスポンスのクラス。インスタンス生成時に引数にテキストを指定したテキストがレスポンスボディ―になり、直接表示される。
テキストのほか、イテレーターやファイルも指定できる。
|
1 2 3 4 |
from django.http import HttpResponse def http_response_text(request): return HttpResponse('<h1>HttpResponse Test</h1>') |
render
renderはdjango.shortcutsパッケージのモジュールで、指定したテンプレートファイルの内容をHttpRequestインスタンスとして返す。
テンプレートファイルに加えて、テンプレートに引き渡す変数コンテキストも指定できる。
|
1 2 3 4 |
from django.shortcuts import render def target(request): return render(request, 'appname/target.html') |
リダイレクト
HttpResponseRedirect
HttpResponseRedirectはdjango.httpパッケージのモジュールで、指定したURLに遷移するためのHTTPレスポンスのインスタンスを生成する。
HttpResponseRedirectはHttpResponseRedirectBaseを継承し、HttpResponseRedirectBaseはHttpResponseを継承している。
ビュー関数/メソッドの中で、URLを引数に与えてHttpResponseRedirectのインスタンスを生成し、戻り値にそのインスタンスを渡すことで、指定したURLにリダイレクトされる。
引数のURLは以下のように与えることができる。
- ホスト名を含む絶対URL
- アプリケーション名から始まるサブディレクトリーによる相対URL
urls.pyのpath関数で設定したルート名をreverse関数の引数に与えた戻り値(ルート名を直接与えることはできない)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
from django.http import HttpResponseRedirect # 絶対URL指定 def http_response_redirect_absolute(request): return HttpResponseRedirect('http://localhost:8000/appname/target') # アプリケーション相対URL指定 def http_response_redirect_relative(request): return HttpResponseRedirect('/appname/target') # urls.pyのルート名もreverse関数を通して指定可能 def http_response_redirect_name(request): return HttpResponseRedirect(reverse('appname:target')) # return HttpResponseRedirect('appname:target') -> ERROR! # 直接ルート名は指定できない |
redirect
redirectはdjango.shortcutsパッケージのモジュールで、指定したURLにリダイレクトするためのHTTPレスポンのためのスインスタンスを返す。
redirectは関数として定義され、デフォルトではHttpResponseRedirectのインスタンスを返すが、引数にpermanent=Trueを設定すると、HttpResponsePermanentRedirectのインスタンスを返す(このクラスは301ステータスを返す)。
redirectがHttpResponseRedirectを返す際、resolve_url関数を介していて、reverse関数を使わず直接ルート名を渡すことができる。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
from django.shortcuts import redirect # 絶対URL指定 def redirect_absolute(request): return redirect('http://localhost:8000/appname/target') # アプリケーション相対URL指定 def redirect_relative(request): return redirect('/appname/target') # ルート名も指定可能 def redirect_name(request): return redirect(reverse('appname:target')) # return redirect('appname:target') -> OK! # ルート名のみを指定してもよい |