Djangoで、テンプレートを利用して画面を表示させていきます。
環境
- Windows10
- Django 2.1.4
- sqlite3
テンプレートとは?
簡単にいうなら、Djangoで使うhtmlファイルのことです。
実際にはor文、if文などをDjangoの機能が使えるようになったhtmlです。
Djangoではテンプレートを使ってwebブラウザで開く画面を表示させます。
フォルダ構成
フォルダ構成は下記の通りです。
プロジェクト名 [example]
アプリケーション名[testapp]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
example │ db.sqlite3 │ manage.py │ ├─example │ │ settings.py │ │ urls.py │ │ wsgi.py │ │ __init__.py │ │ │ └─testapp │ admin.py │ apps.py │ models.py │ tests.py │ urls.py │ views.py │ __init__.py |
テンプレートの使い方
テンプレートを作る
まずは、テンプレートを作ります。
testapp直下にtemplatesフォルダを作り、そこにテンプレートのindex.htmlを作ります。
index.html
1 2 3 4 5 6 7 8 9 |
<!DOCTYPE html> <html> <head> <title>タイトル</title> </head> <body> This is Template </body> </html> |
テンプレートを呼ぶメソッドを作る
次にtestapp/views.pyにテンプレートを呼び出すメソッドを追加します。
views.py
1 2 3 4 5 6 7 |
from django.http import HttpResponse from django.shortcuts import render def index(request): # テンプレートを返却 return render(request, 'index.html') |
パスの設定
最後にurlの設定をします。
testapp/urls.pyにパスの設定を加えます。
urls.py
1 2 3 4 5 6 7 |
from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), #パスの追加 ] |
これで、http://127.0.0.1:8000/testapp/にブラウザでアクセスするとindex.htmlのページが表示されます。