環境
- Python 3.6.10
- Django 3.0.8
準備
まずはDjangoの準備を進めていく。
任意のディレクトリに移動して以下のコマンドでプロジェクト作成。
django-admin startproject testClassBasedView
cd testClassBasedView
django-admin startapp myapp
settings.pyファイルを少し書き換えておく。
testClassBasedView/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# 作成したアプリの追加
'myapp',
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')], #ここを変更
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
# 言語設定。別にしなくてもなんら問題はない。
LANGUAGE_CODE = 'ja'
# 時間の設定。上に同じ
TIME_ZONE = 'Asia/Tokyo'
これでrunserverしてlocalhost:8000にアクセスしてDjangoのスタートページが表示されたら準備は完了!
url
まずはurlから設定していく。プロジェクトのurls.pyにアプリの方のurls.pyに行くように仕向ける。
testClassBasedView/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls'))
]
これでadminにリクエストが投げられると管理者ページを表示する。それ以外のurlにリクエストが来るとmyappのurl.pyを探しに行く。なので次はアプリの方のurlを設定してあげる必要があるってわけ。
myapp/urls.py
from django.urls import path
from .views import TestView
urlpatterns = [
path('', TestView.as_view(), name='home')
]
アプリの方のurls.pyはこんな感じにしておく。localhost:8000にリクエストが来るとTestViewに書いてある処理が実行される。
Viewを作る
GET
ここからが本題。Viewをクラスで作っていく。まずはこんな感じにしてみる。
myapp/views.py
from django.views import View
from django.shortcuts import render
class TestView(View):
template_name = 'home.html'
viewMojiretu='from view'
def get(self, request):
return render(request, self.template_name {'htmlMojiretu':self.viewMojiretu})
このクラスがViewとして呼び出された時、template_nameにhome.htmlを格納。viewMojiretuという変数に'from views'という値を格納している。で、GETで先ほど設定したurlにリクエストが来た場合は関数getの中身が実行される。ここでは使用するtemplateとしてtemplate_nameを指定し、templateにhtmlMojiretuとしてviewMojiretuを渡すことでhtmlファイルでhtmlMojiretuを使って'from view'という文字列を表示することができる。templatesフォルダの中にhome.htmlを作成し、内容は以下の通りにする。
templates/home.html
<p>{{ htmlMojiretu }}</p> <!-- ここに'from view'と表示される -->
これでもう一度runserverし、localhost:8000にアクセスするとfrom viewと表示されているはず。
POST
次にPOSTでリクエストを受けたときの処理を書いていく。まずはPOSTでリクエストを送れるようにhome.htmlを編集していく。
templates/home.html
<p>{{ htmlMojiretu }}</p> <!-- ここに'from view'と表示される -->
<p>好きな数字を入力してね。</p>
<form action="/" method="POST">{% csrf_token %}
<input type="number" name="num">
<button>submit</button>
</form>
ポイントとなるのはformのactionとmethodのところ。actionではlocalhost:8000/つまり今と同じurlにリクエストを送りますよと設定している。methodはPOSTを指定。まとめると今と同じurlにPOSTでリクエストを送るからサーバーさん処理してくれってこと。このformではnumという名前で何かしらの数字を送れるようになっている。現時点でTestViewにpostの処理は書かれていないので書き加えていく。
myapp/views.py
from django.views import View
from django.shortcuts import render
# Create your views here.
class TestView(View):
template_name = 'home.html'
viewMojiretu = 'from views'
postMojiretu = 'This is POST'
template_name_post = 'post.html'
def get(self, request):
return render(request, self.template_name, {'htmlMojiretu': self.viewMojiretu})
def post(self, request):
number1=request.POST['num']
return render(request, self.template_name_post, {'htmlPost': self.postMojiretu, 'number2': number1})
postMojiretuとtemplate_name_postを追加。POSTリクエストでこのViewが呼び出された時はpost関数が実行される。number1に送られてきた数字を格納してnumber2としてtemplateに渡す。postで来た場合のtemplateはtemplate_name_postに指定したpost.htmlを使用。post.htmlを編集する。
template/post.html
<p>あなたの好きな数字は{{ number2 }}です</p>
{{ htmlPost }}
まずはブラウザでlocalhost:8000にいき、formに好きな数字を入力してsubmitボタンを押すとpost.htmlで好きな数字が表示される。
感想
DjangoのClass-based viewsについて理解が深まった!