![見出し画像](https://assets.st-note.com/production/uploads/images/21987985/rectangle_large_type_2_71371b8bb9efb4989eea2578fd6f56e4.jpeg?width=800)
Photo by
hiilagram
【35日目】ビュー関数のクラス化【Django】
今日の写真のイメージは「クラス」です。
ビュー関数のクラス化を行おうと思います。
0.今までのView関数
今まで使っていたviews.pyは以下の中身でした。
methondがPOSTの場合、その他の場合、というのをif文で分岐させています。
これだと使い勝手が良くない、ということでクラス化してみよう。という流れのようです。
from django.shortcuts import render
from .forms import ChartForm
def index(request):
params = {
'symbol':"XBTUSD",
'start_date':"2019/1/2",
'end_date':"2020/1/2",
'form':ChartForm(),
}
if (request.method == 'POST'):
params['form'] = ChartForm(request.POST)
return render(request,'chart/index.html', params)
1.これからのView関数
TemplateViewというクラスを継承して作るそうです。
やってみます。あわせて、表示する中身も変えてみました。
TemplateViewのimportを忘れてすごくエラーが出ました。
from django.shortcuts import render
from django.views.generic import TemplateView
from .forms import ChartForm
class ChartView(TemplateView):
def __init__(self):
self.params = {
'msg':"条件を入力してください",
'form':ChartForm(),
}
def get(self,request):
return render(request,'chart/index.html', self.params)
def post(self,request):
self.params['msg']="条件は "+ request.POST["choice_symbol"] + " と "+request.POST["choice_timeframe"] + " です"
self.params['form'] = ChartForm(request.POST)
return render(request,'chart/index.html', self.params)
2.urlpatternsの変更
元々使用していたurlpatternsではviews.pyの中のindexを呼び出していました。この関数がなくなったので対応するように修正。
ChartViewのimportを忘れてすごくエラーが出ました。
<元のviews.py>
from django.urls import path
from . import views
app_name = 'chart'
urlpatterns = [
path('', views.index, name='index'),
]
<新しいviews.py>
from django.urls import path
from .views import ChartView
app_name = 'chart'
urlpatterns = [
path('', ChartView.as_view(), name='index'),
]
良い感じに仕上がりました!
あなたによって僕は生かされている。 私もあなたを生かせられますように。