TemplateViewクラス

TemplateViewクラスを使ってビュー関数をクラス化することで、さらに高度な処理ができるようになる。

TemplateViewクラスの定義

TemplateViewクラスは、ビューを扱う Viewクラスを継承している。

インスタンスで共有する値などはインスタンス変数として定義し、GET時の処理を受け持つgetメソッドと、POST時の処理を受け持つpostメソッドを持つことができる。

class クラス名(TemplateView):

  def get(self, request):
    .....GET時の処理.....

  def post(self, request):
    .....POST時の処理.....

views.pyの修正

hello/views.pyを修正して、HelloViewクラスを作る。

from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import TemplateView
from .forms import HelloForm

class HelloView(TemplateView):

  def __init__(self):
    self.params = {
      'title': 'Hello',
      'message': 'your data:',
      'form': HelloForm()
    }

  def get(self, request):
    return render(request, 'hello/index.html', self.params)


  def post(self, request):
    msg = 'あなたは、<b>' + request.POST['name'] + \
      ' (' + request.POST['age'] + \
      ') </b>さんです。<br/>メールアドレスは <b>' + request.POST['mail'] + \
      '</b> ですね。'
    self.params['message'] = msg
    self.params['form'] = HelloForm(request.POST)
    return render(request, 'hello/index.html', self.params)

__init__ : 初期化メソッド。self.paramsにパラメータ値を保持させるなどの処理はここで

get : GET時の処理。self.paramsをテンプレートに渡してrender

post : POST時の処理。request.POSTから値を取得し、self.params['message']に代入する。request.POSTを引数にしてHelloFormクラスのインスタンスを作成し、self.params['form']に設定してrender

urlpatternsを修正

from django.conf.urls import url
from .views import HelloView

urlpatterns = [
    url(r'', HelloView.as_view(), name='index'),
]

表示結果

http://localhost:8000/hello/にアクセスしてフォームに入力すると次のような表示になった。

Hello

あなたは、Boo (40) さんです。
メールアドレスは boo@example.com ですね。

f文字列(f-string)を使う

views.pymsg変数の文字列処理は、文字列を+で連結しているので、非常に読みづらい。 Python3.6 以上なら f文字列(f-string) という機能があるのでそこだけ変更してみた。多少はすっきりする。

postメソッドのみ掲載

def post(self, request):
    msg = f"あなたは、<b>{request.POST['name']} ({request.POST['age']}) </b>さんです。\
      <br/>メールアドレスは <b>{request.POST['mail']}</b> ですね。"
    self.params['message'] = msg
    self.params['form'] = HelloForm(request.POST)
    return render(request, 'hello/index.html', self.params)