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.py
のmsg
変数の文字列処理は、文字列を+
で連結しているので、非常に読みづらい。 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)