0
0

More than 3 years have passed since last update.

DjangoでWebサイトを立ち上げてみる。Part3〜Templateの作成〜

Last updated at Posted at 2020-01-19

この投稿について

学習しながらの作業を進めておりますので、作業進捗の備忘録、学習効果の向上を目的として記録していきます。

開発環境

  • macOS High Sierra 10.13.6
  • Anaconda 3
  • Python 3.7.7
  • Djnago 3.0.6
  • VisualStudioCode

テンプレートとは

本来、HTMLファイル上にPythonコードを記述することはできませんが、Djangoのテンプレートシステムを活用することで、静的なHTMLに動的なPythonコードを記述することができます。
テンプレートタグを使用したコンテンツの表示等をはじめ、各ページのHTMLの共通部分(ナビゲーションバーなど)の記述をテンプレート(ひな形)として作成しておくことができます。
これを上手に活用することにより、HTMLの開発やメンテナンスが楽ちんになります。

templatesフォルダの作成

今回はアプリケーションフォルダ(first_app)の直下にtemplatesフォルダを作成します。

settings.pyの編集

templatesフォルダの存在をsettings.pyに記述します。

first_project/settings.py
import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATES_DIR = os.path.join(BASE_DIR,'first_app/templates')#追加

##################################

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATES_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',
            ],
        },
    },
]

テンプレートとなるhtmlファイルを作成

templatesフォルダ内にbase.htmlを作成し、以下のように記述。

templates/base.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>First App</title>
</head>
<body>
    <h1>Hello this is base.html!</h1>
    {% block bodyblock %}
    {% endblock %}
</body>
</html>

{% block bodyblock %}{% endblock %}という記述がありますが、このブロックタグで囲まれた部分が自由にHTMLの記述を挿入できる箇所になります。

例えばindex.htmlを作成し、以下のように書きます。
```html:templates/index.html
{% extends 'base.html' %}

{% block bodyblock %}

{{ insert_me }}


{% endblock %}
``
{% extends 'base.html' %}の記述によりbase.htmlの記述を読み込んでいます。
また、ブロックタグ内に

{{ insert_me }}

と記述したものが、
base.html`のブロックタグ内に挿入されて表示されることになります。

views.pyファイルを編集

先ほど作成したindex.html内に
views.pyに処理を記述することで、{{}}に囲まれた箇所に指定したレスポンスを返すことができます。
以下のコードでは{{}}タグにつけた名前insert_meの部分を'Hello I am from views.py!'と置き換えるよう記述されています。
置き換える対象については辞書型にまとめることができるみたいです。
return render()の部分で、index.htmlにたいして置き換えの処理を行ない、htmlを生成しています。

first_project/first_app/views.py
from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.

def index(request):
    #return HttpResponse('Hello World!!')
    my_dict = {'insert_me':'Hello I am from views.py!'}
    return render(request,'index.html',context=my_dict)

サーバーを立ち上げて動作確認

first_project/
python3 manage.py runserver

エラーが出る場合はPythonのバージョンが古い場合があります。
その場合はpython3のコマンドで実行するとうまくいきました。

http://127.0.0.1:8000/
にアクセスし、
Hello this is base.html!
Hello I am from views.py!
と表示されていればOK

手順

1 templatesフォルダ作成
2 settings.pyにtemplatesフォルダを登録
3 templatesフォルダ内にテンプレート(HTML)を作成
4 views.pyにtemplateに処理を記述

0
0
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
0
0