ぎじゅメモ

パソコンオタクのメモブログです。

Djangoサーバでテンプレートを表示させてみる

テンプレートを使う

htmlファイルとか、表示させてみよう

Mac + virtualenv + Djangoでサーバーを立ててみる を先に読む事をお勧めします。

筆者の環境

1.設定ファイルにテンプレートを置くフォルダを指定

settings.pyのTEMPLATESを編集する。

以下のように変更

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(BASE_DIR, 'templates'),
        ],
        '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',
            ],
        },
    },
]

templatesディレクトリを指定しています。

2.テンプレートを置くディレクトリを作成

urls.pyとかsettings.pyがあるところにディレクトリを作成します。

$ mkdir templates

3.index.htmlを作成

templatesディレクトリ内にhtmlファイルを作成します。

$ cd templates
$ vi index.html

下記、index.htmlの内容

<html>
<body>
hello!!!!!!!
</body>
</html>

4.view関数からテンプレートを使う

views.pyに一行追加

from django.http.response import HttpResponse
from django.shortcuts import render # 追加する

views.pyに下記二行を追加 render関数を使ってウェブレスポンス(テンプレートファイル)を返すようにする

def hello_template(request):
    return render(request, 'index.html')

urls.pyに一行追加 index.htmlを呼び出せるようにする

    url(r'^$', views.hello_world, name='hello_world'),
    url(r'^template/$', views.hello_template,name='hello_template'),  # 追加する

5.サーバー実行してみる

manage.pyのあるディレクトリに移動してから下記コマンドを実行する

$ python manage.py runserver

ブラウザで http://127.0.0.1:8000/[プロジェクト名]/template/ にアクセスしてみる。 画面上にindex.htmlの内容が表示されればOK!

思った事

初めてだからかもしれないけどExpressやRailsに比べてめんどくさかった

参考:https://eiry.bitbucket.io/tutorials/tutorial/templates.html