DEV Community

kaede
kaede

Posted on

Django Tutorial Part 7 -- template を使う

何をするのか

Django Tutorial の template 編

https://docs.djangoproject.com/en/4.0/intro/tutorial03/#write-views-that-actually-do-something

projectName/settings.py の TEMPLATES/'APP_DIRS' を False にしていると

TemplateDoesNotExist at /polls/

で読み込めなくなる。


views.py の index で template と context(Question) をセットする

from django.http import HttpResponse from django.template import loader from .models import Question def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] template = loader.get_template('polls/index.html') context = { 'latest_question_list': latest_question_list, } return HttpResponse(template.render(context, request)) 
Enter fullscreen mode Exit fullscreen mode
  • HTTP レスポンスを返すための HttpResonse
  • template を読み込むための loader
  • Question テーブルを読み込むための .models

これらをインポート

Question テーブルの中身をリストで取ってきて、日付で並べ替え、5つまでに制限して
(polls/template/の) polls/index.html を読み込み
context として上記のリストをオブジェクトとしてセットする
そして、テンプレートで context と共に request の response を返す。

https://docs.djangoproject.com/en/4.0/intro/tutorial03/#a-shortcut-render

loader の代わりのに render を使うやり方もある。

from django.shortcuts import render ... render(request,'polls/index.html', context) 
Enter fullscreen mode Exit fullscreen mode

render のライブラリを使って、
直接 template 配下のファイルを読み込んで template として渡すことができる。request と context は同じ。


template フォルダを作って index.html を作成する

polls アプリに

polls/templates/polls/index.html

として html ファイルを作る

{% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} 
Enter fullscreen mode Exit fullscreen mode

Django は {% %} のブロックでロジックをかける。
if と else で条件の True False によって見せる方を変えられる
for と endfor で context で渡されたリストをリンク当てて展開する。


ブラウザで確認する

Image description

Image description

template が表示されて、詳細にも飛べた。

Top comments (0)