### 特定のIDのみ取り出す
/hello/forms.py
from django import forms class HelloForm(forms.Form): id = forms.IntegerField(label='ID')
/hello/templates/hello/index.html
<body class="container"> <h1 class="display-4 text-primary">{{title}}</h1> <p class="h5 mt-4">{{message|safe}}</p> <form action="{% url 'index' %}" method="post"> {% csrf_token %} {{ form}} <input type="submit" value="click"> </form> <hr> <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>
– Friend.objects.get(id=num)でレコードを一つ取り出す
– Managerクラスが取り出している
/hello/views.py
from django.shortcuts import render from django.http import HttpResponse from .models import Friend from .forms import HelloForm def index(request): params = { 'title': 'Hello', 'message': 'all friends.', 'form': HelloForm(), 'data': [], } if(request.method == 'POST'): num=request.POST['id'] item=Friend.objects.get(id=num) params['data'] = [item] params['form'] = HelloForm(request.POST) else: params['data'] = Friend.objects.all() return render(request, 'hello/index.html', params)
views.pyの関数がMVCのコントローラみたいな役割をしてますね。