はじめに
この講座を見てDjangoの勉強をしています。
今後の開発のために簡潔に開発の流れをまとめました。
その3です。
ここではtemplates
フォルダの移動の仕方を学びます。
開発環境構築の流れ(続き)
templates
フォルダを移動する
外側のsample_project
内にtemplates
フォルダを作成する
さらにtemplates
フォルダ内にさらにindex.html
を追加する
index.html
<h1>移動できた</h1>
settings.py
を修正する
先ほど作成したtemplates
フォルダ内を参照するようにしていきます。
14行目くらい
from pathlib import Path
+ import os
↑下の記述に必要
17行目くらい
BASE_DIR = Path(__file__).resolve().parent.parent
+ TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')
イメージは下のような式と同じ。
TEMPLATE_DIR = "BASE_DIR/templates"
BASE_DIR
内のtemplates
フォルダをデフォルトで認識してくれるようにしたい。
その設定に用いるパラメータTEMPLATE_DIR
を設定した。
そして下の変更で実際に設定する。
59行目くらい
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
- "DIRS": [],
+ "DIRS": [TEMPLATE_DIR,],
"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",
],
},
},
]
views.py
を修正する
def index(request):
- return render(request, 'appapp/index.html')
+ return render(request, 'index.html')
自動でtemplates
フォルダを見てくれるようになっているので、templates/index.html
などとしない。
実行確認
$ python manage.py runserver
urlの末尾にsample_app
と追加して実行。「移動できた」と表示されればおk
今後のために少し変更
templates
フォルダの直下にindex.html
ファイルを置いていたが、もう1階層下げる。
template_app
フォルダを作成し、その中にindex.html
を移動する
views.py
を修正する
def index(request):
- return render(request, 'index.html')
+ return render(request, 'template_app/index.html')
実行確認
$ python manage.py runserver
urlの末尾にsample_app
と追加して実行。「移動できた」と表示されればおk