TemplateView - Django

TemplateViewとは

特定のテンプレートを描画する際に使用され、URL パターンと対応するテンプレートを指定するだけで、ビューを作成できます。

ファイル内容

pythonApp\view\view\view\settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'hello', # +
]

pythonApp\view\view\hello\templates\hello\index.html

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <h1>hello/index</h1>
</body>
</html>

pythonApp\view\view\hello\urls.py

as_view() メソッドは、リクエストに対してビュー関数を返します。

from django.urls import path
from . import views

app_name = 'hello'

urlpatterns = [
    path("", views.IndexView.as_view(), name="index")
]

pythonApp\view\view\view\urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('hello/', include('hello.urls')),
]

pythonApp\view\view\hello\views.py

from django.views.generic import TemplateView

class IndexView(TemplateView):
  template_name = "hello/index.html"

get_context_date

get_context_date は、クラスベースビューに実装されたメソッドの1つで、GET(HTTP メソッド) の時に呼び出されるメソッドです。

クラスベースビューを使用時、テンプレートに変数を渡す場合は、get_context_data を使う必要があります。

pythonApp\view\view\hello\views.py

from django.views.generic import TemplateView

class IndexView(TemplateView):
  template_name = "hello/index.html"

  def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs) #親クラスのメソッドを実行
    context['hello'] = "Hello, World" 
    return context

pythonApp\view\view\hello\templates\hello\index.html

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <h1>hello/index</h1>
  <p>{{ hello }}</p>
</body>
</html>