LoginSignup
2
2

More than 1 year has passed since last update.

Django HTMLファイルの表示と変数の渡し方

Last updated at Posted at 2022-05-18

前の記事の確認はこちら

必要なフォルダを作成後、htmlファイル作成

  1. migrationsと同じ階層に【templates】フォルダを作成
  2. templatesフォルダの下に【好きな名称(今回はappとする)】フォルダ作成
  3. app内に【index.html】を作成
app名フォルダ
|
|- migrations
|
|- templates - app - index.html
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Django練習</title>
</head>
<body>
    <h1>Hello Django</h1>
</body>
</html>

views.pyの編集

views.py
# renderのインポート
from django.shortcuts import render

# render関数で、さっき作ったappフォルダにあるinde.htmlを指定
def index(request):
    return render(request, 'app/index.html')

runserverで確認

python manage.py runserver

(URLは http://127.0.0.1:8000/app/)
スクリーンショット 2022-05-19 7.31.27.png

htmlファイルに変数を渡す

views.pyにデータをセット

views.pyに辞書でデータをセット(context部分)
returnの第3引数にセットしたcontextを渡す

from django.shortcuts import render

def index(request):
+    context = {
+        "name": "Yamada",
+        "age": 12
+    }
-    return render(request, 'app/index.html')
+    return render(request, 'app/index.html', context)

index.htmlにデータをセット

データを表示させるには、
{{ }}で使用したいデータにセットしたキーを指定する

index.htmlファイル↓

<body>
    <h1>Hello Django</h1>
+    <p>私は{{ name }}です。</p>
+    <p>{{ age }}になりました。</p>
</body>

スクリーンショット 2022-05-19 7.47.50.png

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2