### レコードの表示
– data = Friend.objects.all() で取り出す
/hello/views.py
from django.shortcuts import render from django.http import HttpResponse from .models import Friend def index(request): data = Friend.objects.all() params = { 'title': 'Hello', 'message': 'all friends.', 'data': data, } return render(request, 'hello/index.html', params)
– {% for item in data %}{% endfor %}で繰り返し処理
– {% if %}{% endif %}で条件分岐
/hello/templates/hello/index.html
<body class="container"> <h1 class="display-4 text-primary">{{title}}</h1> <p class="h5 mt-4">{{message|safe}}</p> <table class="table"> <tr> <th>ID</th> <th>NAME</th> <th>GENDER</th> <th>MAIL</th> <th>AGE</th> <th>BIRTHDAY</th> </tr> {% for item in data %} <tr> <td>{{item.id}}</td> <td>{{item.name}}</td> <td>{% if item.gender == False %} male{% endif%} {% if item.gender == True %} female{% endif%}</td> <td>{{item.mail}}</td> <td>{{item.age}}</td> <td>{{item.birthday}}</td> </tr> {% endfor %} </table> </body>
/hello/urls.py
from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ]
おおお、いいですね。MVCを触ってる感が出てきました。