LoginSignup
9
9

More than 5 years have passed since last update.

はじめてのDjangoに最適、簡単なテンプレートを表示させてみる

Last updated at Posted at 2016-10-21

Djangoに慣れてみるには

そもそもSQLだとか、なんだとかわかりにくすぎるのが問題なんじゃないかと。
いきなりデータベースに接続してアプリケーションウンタラカンタラ・・・。個人的には敷居が高すぎる気がしました。

初歩の初歩はbottleでもやったとおり、まずはテンプレートを作り、HTMLを表示させてみるところからなんじゃないかと思いついたのでやったことをまとめておきます。

前回からの続き

http://qiita.com/Gen6/items/1848f8b4d938807d082e

まずはテンプレートを格納するディレクトリを作りましょう。
mysite/ 直下に templates というディレクトリを作ります。

わかりやすく画面キャプチャしてみました。

スクリーンショット 2016-10-21 15.19.37.png

早速基本的な設定をしていきます。

設定ファイルなどに記述を加えていく

myapp/urls.py
from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^template/$', views.index, name='index'), 
]
mysite/settings.py
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/index.html
<!DOCTYPE html>
<html>
 <head lang="ja">
    <meta charset="UTF-8">
    <title></title>
 </head>
 <body>
  <p>welcome template</p>
 </body>
</html>
myapp/views.py
from django.http.response import HttpResponse
from django.shortcuts import render


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

ここまで出来ればOK。

$ cd Djangoproject
$ source virtualenv/bin/activate
$ cd mysite
$ python manage.py runserver

にindex.htmlが表示されれば完成です。

なお、テンプレートは継承という方法もあるのでその場合は templates ディレクトリに main.htmlを以下のように作成します。

templates/main.html
<!DOCTYPE html>
<html>
  <head lang="ja">
    <meta charset="UTF-8">
    <title></title>
  </head>
  <body>
    {% block body %}
    {% endblock %}
  </body>
</html>

そしてindex.htmlを以下のように書き直し完了。

templates/index.html
{% extends "main.html" %}
{% block body %}
  <p>welcome template</p>
{% endblock %}
9
9
1

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