Viewの編集
「test_app/views.py」を以下のように変更します。
# test_app/views.py from django.shortcuts import render from django.contrib.auth.models import User # ShareCode を使うためにインポート from .models import ShareCode def top_page(request): # ShareCodeの全行を取得 share_codes = ShareCode.objects.all() context = { 'message': 'Test from view', 'database_object': share_codes, # 辞書contextにshare_codesを入れる } return render(request, 'test_app/top_page.html', context)
テンプレートの編集
テンプレートのtop_page.htmlを以下のように記述します。
<!-- test_app/templates/test_app/top_page.html --> <!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <title>トップページ</title> </head> <body> <h1>ようこそ、トップページへ!</h1> <p>Djangoのrenderでこのテンプレートが表示されています。</p> {% for code in database_object %} <li>{{ code.title }}</li> <li>{{ code.code }}</li> <li>{{ code.description }}</li> <li>{{ code.creator }}</li> {% endfor %} </body> </html>
解説
{% for code in database_object %}
{% endfor %}
Viewから受け取ったdatabase_objectの要素を一番後ろのものまで順番に code にいれます。
{{ code.title }}
code内のtitleを取得して表示させます。
「http://127.0.0.1:8000/」にアクセスすると以下のようにDBの情報が表示されます。

コメント