検証環境
- Python 3.10.8
- Django 4.1.4
はじめに
本稿では、Djangoでhtmlファイルをレンダリングする方法を説明する。
Djangoのインストールや基本的な使い方は以下の記事を参考にしたい。
[Python] Django 入門
ファイル構成
mysiteプロジェクトの構成は以下になる。
% ls
manage.py* myapp/ mysite/
% ls mysite
__init__.py __pycache__/ asgi.py settings.py urls.py wsgi.py
% ls myapp
__init__.py __pycache__/ admin.py apps.py migrations/ models.py static/ templates/ tests.py urls.py views.py
myapp 内で今回使用するのもは以下になる。
- views.py
ビューを記述する - urls.py
urlを記述する - templates/
htmlファイルを格納する - static/
cssやJavaScriptなどのhtmlで読み込ませるファイルを配置する
設定
アプリケーションを認識させるために、setting.py の INSTALLED_APPS に設定を施す必要がある。
myapp アプリケーションを認識させるには、myapp/apps.py に記述されている MyappCofing クラスを INSTALLED_APPS に追加する。
# mysite/settings.py
...
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.apps.MyappConfig', # ここ
]
...
htmlファイルの作成
htmlファイルは、myapp/templates/ 配下に配置する。
% ls myapp/templates
index.html
<!-- index.html -->
<!DOCTYPE html>
<html lang="ja">
<head>
</head>
<body>
<h1>Hello from index.html</h1>
</body>
</html>
ビューの作成
htmlファイルをレンダリングするには、render関数を使用する。
# myapp/views.py
from django.shortcuts import render
def index(request):
return render(request, "index.html")
上記のようにすることで、templates/index.html を読み込み、レンダリングすることができる。
URLの設定
URLの設定をする。
# mysite/urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path(r'^admin/', admin.site.urls),
path(r'', include('myapp.urls')),
]
# myapp/urls.py
from django.urls import path
from . import views
urlpatterns = [
path(r'', views.index, name='index'),
]
実行し、設定したURLにアクセスする。
% python3 manage.py runserver
localhost:8000
cssやJavaScriptの読み込み
開発環境の場合
「mysite/settings.py」の DEBUG が True なことを確認する。
DEBUG = True
cssやJavaScriptファイルは、myapp/static ディレクトリ配下に配置する。
% ls myapp/static
index.css index.js
/* index.css */
h1 {
color: red;
}
// index.js
window.onload = function() {
var e = document.getElementById('test');
e.style.color = 'blue';
}
staticディレクトリ配下のファイルを読み込むには、まず {% load static %} でロードする必要がある。
次に以下のように記述することで、各ファイルを読み込むことができる。
<!-- myapp/templates/index.html -->
<!DOCTYPE html>
<html lang="ja">
<head>
{% load static %}
<link rel="stylesheet" href="{% static 'index.css' %}" />
<script src="{% static 'index.js' %}"></script>
</head>
<body>
<h1>Hello</h1>
<h2 id='test'>World</h2>
</body>
</html>
これを実行した画面が以下になる。
運用時の場合
別記事で解説する。
0件のコメント