LoginSignup
4

More than 5 years have passed since last update.

DJangoメモ:はじめから(テンプレートからビューを作る編)

Last updated at Posted at 2013-12-14

いよいよテンプレートを使ってページを作っていきます。

テンプレートの在処を設定

setting.py
TEMPLATE_DIRS = (
    'path/to/your/templates'    # どこでもいいっぽい
)

当然だが、設定したらちゃんとその場所を用意しないと駄目。

テンプレートを作成

テンプレートディレクトリが準備できたら、そこにさらにアプリごとのサブディレクトリを作ってその中にHTMLテンプレートを作っていく。
今回は「polls」の中にindex.htmlを作成。

index.html
{% if latest_poll_list %}
    <ul>
    {% for poll in latest_poll_list %}
        <li><a href="/polls/{{ poll.id }}/">{{ poll.question }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>No polls are available.</p>
{% endif %}

Pythonプログラムの間にHTMLが入ってきている。{% hoge … %}から{% endhoge %}までが一つ一つの処理か。
その内側に{{ }}で囲われた部分もあるがこれはPHPでいうechoみたいなものかもしれない。HTMLにそのまま値を返す感じだと思われる。

テンプレートをビューに指定

テンプレートが出来たら、これを該当ページのビューとして設定する。

views.py
from django.template import Context, loader
from polls.models import Poll
from django.http import HttpResponse

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    temp = loader.get_template('polls/index.html')
    contxt = Context({
        'latest_poll_list': latest_poll_list,  # 最新のものを表示?
    })
    return HttpResponse(temp.render(contxt))

また、shortcutsのモジュールを使えば以下のように短く書くこともできるらしい。

from django.shortcuts import render_to_response
# これを使うことでtemplateとhttpが不要に
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html',
                              {'latest_poll_list': latest_poll_list})
    # 前のコードのtempとcontxtをまとめた感じでreturnしている?

個人的には、長くても前の書き方のほうが好み(分かりやすいので)。
ショートカットは慣れてきてから使いたい。

ところで、釈然としない点がふたつあったので挙げておく

1.’-pub_date’:最初のハイフンは何を意味しているのか?

2.[:5]:同じくコロンが意味不明。

次回はエラー画面の設定から再開します。

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
4