LoginSignup
8
7

More than 1 year has passed since last update.

Djangoのviews.pyのredirect、render等の違い

Last updated at Posted at 2020-12-06

この記事の内容

Djangoのviews.pyの中でreturnしているrender等の違いについて説明します。

・render
・redirect
・TemplateResponse

render

Djangoのドキュメント
"Combines a given template with a given context dictionary and returns an HttpResponse object with that rendered text."

特徴:redirectとの違いはtemplates(html)に変数等を渡せる。
動き:renderで記述した内容をHttpResponseに渡すことでレンダリングします。
(DjangoではHttpResponse等の中身によってレンダリングしている。
そのHttpResponseをより便利に使うためのもの)

renderの記述例
from django.shortcuts import render

def my_view(request):
    # View code here...
    return render(request, 'myapp/index.html', {
        'foo': 'bar',}) #第三引数に辞書型で渡す値を指定する

redirect

Djangoのドキュメント
"Returns an HttpResponseRedirect to the appropriate URL for the arguments passed."

特徴:templates(html)に何も渡さない。
単に対象のURLに遷移したいときに使用する。
下の例では、単にhttps://example.com/を表示する。

動き:HttpResponseRedirectを便利に使うための機能。
HttpResponseRedirectはステータスコード302を返すため、
redirectを使用すると、ステータスコード302が返ります。

redirectの記載例
return redirect('https://example.com/')  

TemplateResponse

Djangoのドキュメント
"Django does not provide a shortcut function which returns a TemplateResponse because the constructor of TemplateResponse offers the same level of convenience as render()."

Djangoのドキュメントによると、renderと同じくらい便利なため、TemplateResponseのショートカット機能を用意していないのことです。
renderとの違いは、viewの処理が終わるまでレンダリングをしないことです。
これにより、settings.pyに記載されているMiddleWareが起動後にレンダリングが始まる利点があります。

TemplateResponseの記載方法
from django.template.response import TemplateResponse

TemplateResponse.__init__(request, template, context=None, content_type=None, status=None, charset=None, using=None)

参考サイト

https://docs.djangoproject.com/en/3.1/topics/http/shortcuts/#django.shortcuts.render
https://docs.djangoproject.com/en/3.1/ref/template-response/
https://stackoverflow.com/questions/38838601/django-templateresponse-vs-render
https://nihaoshijie.hatenadiary.jp/entry/2015/08/30/174206

8
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
7