30代初心者インフラエンジニア Django 超入門 

<H1>一日目</H1>
djangoのインストール

```bat
pip install Django==3.0.4 
//バージョン指定はしなくてもいい
```
プロジェクトの作成

```bat
django-admin startproject django_app
//django_appとゆうプロジェクト作成
```
サーバーの起動
```bat
cd django_app
python manage.py runserver
//ブラウザでhttp://localhost:8000
```
![djang.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1614609/67c021b4-e6a0-000b-c2b1-036d70857c42.png)

<H1>二日目</H1>
アプリケーションの作成

```bat
python manage.py startapp hello
//helloとゆうフォルダが作成される
```
view.pyを編集する

```python
from django.shortcuts import render
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello Django!!")
```
hello/urls.pyを作成、編集する

```python
from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),　#indexとゆう名前を付与
]
```

プロジェクト直下/urls.pyを編集する

```python
from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
        path('hello/', include('hello.urls')), #helloアプリのurlsを全て読み込み
]
#http://localhost:8000/helloをブラウザで確認
```
![djang.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1614609/2821a277-dbac-c12c-67d6-3e95ad3f5037.png)

urlのクエリパラメーターを利用するhello/urls.pyとhello/view.pyを編集する
```python:hello/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('<int:id>/<nickname>/', views.index, name='index'),
    #基本文字列なのでintを指定
]
```
```python:hello/views.py
from django.shortcuts import render
from django.http import HttpResponse

def index(request, id, nickname):
    result = 'your id: ' + str(id) + ', name: "' \　#見かけの改行　次の行も同じになる
        + nickname + '". '
    return HttpResponse(result)
#http://localhost:8000/hello/id/nicknameをブラウザで確認
```
![djang.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1614609/769657fb-a1b9-89af-07cb-7f187994d5ba.png)

<H1>三日目</H1>
templatesをつかう

```python:setting.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'hello', #これを足す
]
```

フォルダを作成して、
index.htmlを作成、
urls.pyの修正、
views.pyのindex関数の修正
```html:hello/templates/hello/index.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>hello</title>
</head>
<body>
    <h1>hello/index</h1>
    <p>This is sample page.</p>
</body>
</html>
```

```python:hello/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
]
```

```python:hello/views.py
from django.shortcuts import render
from django.http import HttpResponse

def index(request):
    return render(request, 'hello/index.html')
```

テンプレートに値を渡す
```html:hello/templates/hello/index.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>{{title}}</title>
</head>
<body>
    <h1>{{title}}</h1>
    <p>{{msg}}</p>
</body>
</html>
```

```python:hello/views.py
from django.shortcuts import render
from django.http import HttpResponse

def index(request):
    params = {
        'title':'Hello/Index',
        'msg':'これは、サンプルぺーじです'
    }
    return render(request, 'hello/index.html', params)
```
複数ページの移動

```html:hello/templates/hello/index.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>{{title}}</title>
</head>
<body>
    <h1>{{title}}</h1>
    <p>{{msg}}</p>
    <p><a href="{% url goto %}">{{goto}}</a></p>
</body>
</html>
```

```python:hello/views.py
from django.shortcuts import render
from django.http import HttpResponse

def index(request):
    params = {
        'title':'Hello/Index',
        'msg':'これは、サンプルぺーじです',
        'goto':'next',
    }
    return render(request, 'hello/index.html', params)

def next(request):
    params = {
        'title':'Hello/Next',
        'msg':'これは、もう一つのぺーじです',
        'goto':'index',
    }
    return render(request, 'hello/index.html', params)
```

```python:hello/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('next', views.next, name='next'),
]
```

cssを使う、静的ファイルの管理、
staticフォルダの作成、bootstrapの使い方
```css:hello/static/css/style.css
body{
    color:gray;
    font-size:16pt;
}

h1{
    color:red;
    opacity: 0.2;
    font-size: 60pt;
    margin-top: -20px;
    margin-bottom: 0px;
    text-align: right;
}

p{
    margin: 10px;
}

a{
    color: blue;
    text-decoration: none;
}
```

```html:hello/templates/hello/index.html
{% load static %}
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>{{title}}</title>
    <link rel="stylesheet" type="text/css"
        href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" crossorigin="anonymous">
</head>
<body class="container">
    <h1 class="display-4 text-primary mb-4">{{title}}</h1>
    <p class="h5">{{msg}}</p>
    <p class="h6"><a href="{% url goto %}">{{goto}}</a></p>
</body>
</html>
```
![djang.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1614609/43a1e0eb-6d20-0884-2c41-66f353fe8733.png)

<H1>四日目</H1>
formをつかう,
hello/forms.pyを作る

```python:hello/forms.py
from django import forms

class HelloForm(forms.Form):
    name = forms.CharField(label='name',widget=forms.TextInput(attrs={'class':'form-control'}))
    mail = forms.CharField(label='mail',widget=forms.TextInput(attrs={'class':'form-control'}))
    age = forms.IntegerField(label='age',widget=forms.NumberInput(attrs={'class':'form-control'}))
#widgetでbootstrapのcssを引数で渡して、htmlでの編集をなくしている
```

```python:hello/views.py
from django.shortcuts import render
from django.http import HttpResponse
from .forms import HelloForm

def index(request):
    params = {
        'title':'Hello',
        'msg':'your data:',
        'form':HelloForm()
    }
    if(request.method == 'POST'):
        params['message'] = '名前:' + request.POST['name'] + \
            '<br>メール:' + request.POST['mail'] + \
            '<br>年齢:' + request.POST['age']
        params['form'] = HelloForm(request.POST)
    return render(request, 'hello/index.html', params)
#indexの中でGETの表示とPOSTの表示を分けている
```

```python:hello/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
]
#indexだけで処理しているため
```

```html:hello/templates/hello/index.html
{% load static %}
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>{{title}}</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" crossorigin="anonymous">

</head>
<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.as_p }}
        <input type="submit" class="btn btn-primary my-2" value="click">
    </form>
</body>
</html>
```
![djang.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1614609/17cbc3da-d21c-2887-765c-6fc8d4fe8dd9.png)

<H1>五日目</H1>
モデルとデータベース
Friendモデルクラスの作成

```python:hello/models.py
from django.db import models

class Friend(models.Model):
    name = models.CharField(max_length=100)
    mail = models.EmailField(max_length=200)
    gender = models.BooleanField()
    age = models.IntegerField(default=0)
    birthday = models.DateField()

    def __str__(self):
        return '<Friend:id=' + str(self.id) + ', ' + self.name + '(' + str(self.age) +')>'

```
マイグレーションファイルの作成
```batch
python manage.py makemigrations hello
```
マイグレーションファイルの実行
```batch
python manage.py migrate
```
管理ツールの作成
```batch
python manage.py createsuperuser
```
admin.pyにFriendモデルを追加
```python:hello/admin.py
from django.contrib import admin
from .models import Friend

admin.site.register(Friend)
#http://localhost:8000/adminにアクセス
```
モデルのobjectはmanagerクラスでできている、
QuerySetを使ってデータベースの中身を取り出し編集する。

```python:hello/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
]
```

```python:hello/views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Friend
from django.db.models import QuerySet

def __new_str__(self):
    result = ''
    for item in self:
        result += '<tr>'
        for k in item:
            result += '<td>' + str(k) + '=' + str(item[k]) + '</td>'
        result += '</tr>'
    return result

QuerySet.__str__ = __new_str__

def index(request):
    data=Friend.objects.all().values('id','name','age')
    params = {
        'title':'Hello',
        'data':data,
    }
    return render(request, 'hello/index.html', params)
```

```html:hello/templates/hello/index.html
{% load static %}
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>{{title}}</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" crossorigin="anonymous">

</head>
<body class="container">
    <h1 class="display-4 text-primary">{{title}}</h1>
    <table class="table">
        {{data|safe}}
    </table>
</body>
</html>
```
![djang.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1614609/c9abf237-18e1-ffc5-e19e-761bd5b8527c.png)

<H1>六日目</H1>
ModelFormでDRUDを作成

urls.pyに飛び先を追加
```python:hello/urls.py
from django.urls import path
from . import views
from .views import FriendList
from .views import FriendDetail


urlpatterns = [
    path('', views.index, name='index'),
    path('create', views.create, name='create'),
    path('edit/<int:num>', views.edit, name='edit'),
    path('delete/<int:num>', views.delete, name='delete'),
    path('list', FriendList.as_view()), #☆
    path('detail/<int:pk>', FriendDetail.as_view()), #☆
]
```

forms.pyにクラスを追加
```python:hello/forms.py
from django import forms
from.models import Friend

class HelloForm(forms.Form):
    name = forms.CharField(label='Name', \
        widget=forms.TextInput(attrs={'class':'form-control'}))
    mail = forms.EmailField(label='Email', \
        widget=forms.EmailInput(attrs={'class':'form-control'}))
    gender = forms.BooleanField(label='Gender', required=False, \
        widget=forms.CheckboxInput(attrs={'class':'form-check'}))
    age = forms.IntegerField(label='Age', \
        widget=forms.NumberInput(attrs={'class':'form-control'}))
    birthday = forms.DateField(label='Birth', \
        widget=forms.DateInput(attrs={'class':'form-control'}))

class FriendForm(forms.ModelForm):
    class Meta:
        model = Friend
        fields = ['name','mail','gender','age','birthday']

```

create関数を作成

```python:hello/views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import redirect
from .models import Friend
#from .forms import HelloForm
from .forms import FriendForm


def index(request):
    data = Friend.objects.all()
    params = {
        'title': 'Hello',
        'data': data,
    }
    return render(request, 'hello/index.html', params)

# create model
def create(request):
    if (request.method == 'POST'):
        obj = Friend()
        friend = FriendForm(request.POST, instance=obj)
        friend.save()
        return redirect(to='/hello')
    params = {
        'title': 'Hello',
        'form': FriendForm(),
    }
    return render(request, 'hello/create.html', params)

```

create.htmlを作成
```html:hello/templates/hello/create.html
{% load static %}
<!doctype html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>{{title}}</title>
    <link rel="stylesheet" 
    href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" 
    crossorigin="anonymous">
</head>
<body class="container">
    <h1 class="display-4 text-primary">
        {{title}}</h1>
    <form action="{% url 'create' %}" 
        method="post">
    {% csrf_token %}
        <table class="table">
        {{ form.as_table }}
            <tr><th><td>
                <input type="submit" value="click"
                    class="btn btn-primary mt-2">
            </td></th></tr>
        </table>
    </form>
</body>
</html>
#http://localhost:8000/hello/createにアクセス
```
![djang.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1614609/52697d50-8379-e8c5-4cce-1f009edf63f0.png)

edit関数をつくる
```python:hello/views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import redirect
from .models import Friend
#from .forms import HelloForm
from .forms import FriendForm


def index(request):
    data = Friend.objects.all()
    params = {
        'title': 'Hello',
        'data': data,
    }
    return render(request, 'hello/index.html', params)

# create model
def create(request):
    if (request.method == 'POST'):
        obj = Friend()
        friend = FriendForm(request.POST, instance=obj)
        friend.save()
        return redirect(to='/hello')
    params = {
        'title': 'Hello',
        'form': FriendForm(),
    }
    return render(request, 'hello/create.html', params)

def edit(request, num):
    obj = Friend.objects.get(id=num)
    if (request.method == 'POST'):
        friend = FriendForm(request.POST, instance=obj)
        friend.save()
        return redirect(to='/hello')
    params = {
        'title': 'Hello',
        'id':num,
        'form': FriendForm(instance=obj),
    }
    return render(request, 'hello/edit.html', params)

```

index.htmlを修正

```html:hello/templates/hello/index.html
{% load static %}
<!doctype html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>{{title}}</title>
    <link rel="stylesheet" 
    href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" 
    crossorigin="anonymous">
</head>
<body class="container">
    <h1 class="display-4 text-primary">
        {{title}}</h1>
    <table class="table">
        <tr>
            <th>data</th>
        </tr>
    {% for item in data %}
        <tr>
            <td>{{item}}</td>
            <td><a href="{% url 'edit' item.id %}">Edit</a></td>
        <tr>
    {% endfor %}
    </table>
</body>
</html>
```

edit.htmlを作成
```html:hello/templates/hello/edit.html
{% load static %}
<!doctype html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>{{title}}</title>
    <link rel="stylesheet" 
    href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" 
    crossorigin="anonymous">
</head>
<body class="container">
    <h1 class="display-4 text-primary">
        {{title}}</h1>
    <form action="{% url 'edit' id %}" 
        method="post">
    {% csrf_token %}
        <table class="table">
        {{ form.as_table }}
            <tr><th><td>
                <input type="submit" value="click"
                    class="btn btn-primary mt-2">
            </td></th></tr>
        </table>
    </form>
</body>
</html>
#http://localhost:8000/hello/からeditをクリック
```
![djang.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1614609/4317c0f3-1c4a-577d-de8b-f02b9d7bcfac.png)

delete関数をつくる
```python:hello/views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import redirect
from .models import Friend
#from .forms import HelloForm
from .forms import FriendForm


def index(request):
    data = Friend.objects.all()
    params = {
        'title': 'Hello',
        'data': data,
    }
    return render(request, 'hello/index.html', params)

# create model
def create(request):
    if (request.method == 'POST'):
        obj = Friend()
        friend = FriendForm(request.POST, instance=obj)
        friend.save()
        return redirect(to='/hello')
    params = {
        'title': 'Hello',
        'form': FriendForm(),
    }
    return render(request, 'hello/create.html', params)

def edit(request, num):
    obj = Friend.objects.get(id=num)
    if (request.method == 'POST'):
        friend = FriendForm(request.POST, instance=obj)
        friend.save()
        return redirect(to='/hello')
    params = {
        'title': 'Hello',
        'id':num,
        'form': FriendForm(instance=obj),
    }
    return render(request, 'hello/edit.html', params)

def delete(request, num):
    friend = Friend.objects.get(id=num)
    if (request.method == 'POST'):
        friend.delete()
        return redirect(to='/hello')
    params = {
        'title': 'Hello',
        'id':num,
        'obj': friend,
    }
    return render(request, 'hello/delete.html', params)

```

index.htmlを修正

```html:hello/templates/hello/index.html
{% load static %}
<!doctype html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>{{title}}</title>
    <link rel="stylesheet" 
    href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" 
    crossorigin="anonymous">
</head>
<body class="container">
    <h1 class="display-4 text-primary">
        {{title}}</h1>
    <table class="table">
        <tr>
            <th>data</th>
        </tr>
    {% for item in data %}
        <tr>
            <td>{{item}}</td>
            <td><a href="{% url 'edit' item.id %}">Edit</a></td>
            <td><a href="{% url 'delete' item.id %}">Delete</a></td>
        <tr>
    {% endfor %}
    </table>
</body>
</html>
```

edit.htmlを作成
```html:hello/templates/hello/delete.html
{% load static %}
<!doctype html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>{{title}}</title>
    <link rel="stylesheet" 
    href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" 
    crossorigin="anonymous">
</head>
<body class="container">
    <h1 class="display-4 text-primary">
        {{title}}</h1>
    <p>※以下のレコードを削除します。</p>
    <table class="table">
        <tr><th>ID</th><td>{{obj.id}}</td></tr>
        <tr><th>Name</th><td>{{obj.name}}</td></tr>
        <tr><th>Gender</th><td>
        {% if obj.gender == False %}male{% endif %}
        {% if obj.gender == True %}female{% endif %}</td></tr>
        <tr><th>Email</th><td>{{obj.mail}}</td></tr>
        <tr><th>Age</th><td>{{obj.age}}</td></tr>
        <tr><th>Birth</th><td>{{obj.birthday}}</td></tr>
        <form action="{% url 'delete' id %}" method="post">
        {% csrf_token %}
        <tr><th></th><td>
            <input type="submit" value="click"
                class="btn btn-primary">
        </td></tr>
        </form>
    </table>
</body>
</html>
#http://localhost:8000/hello/からdeleteをクリック
```
![djang.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1614609/fbf8cdc4-94bd-ea67-b243-8260e8cc1ef9.png)


ジェネリックビューの作成
views.pyにimportとクラスを追加

```python:hello/views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import redirect
from .models import Friend
#from .forms import HelloForm
from .forms import FriendForm
from django.views.generic import ListView
from django.views.generic import DetailView

class FriendList(ListView):
    model = Friend

class FriendDetail(DetailView):
    model = Friend


def index(request):
    data = Friend.objects.all()
    params = {
        'title': 'Hello',
        'data': data,
    }
    return render(request, 'hello/index.html', params)

# create model
def create(request):
    if (request.method == 'POST'):
        obj = Friend()
        friend = FriendForm(request.POST, instance=obj)
        friend.save()
        return redirect(to='/hello')
    params = {
        'title': 'Hello',
        'form': FriendForm(),
    }
    return render(request, 'hello/create.html', params)

def edit(request, num):
    obj = Friend.objects.get(id=num)
    if (request.method == 'POST'):
        friend = FriendForm(request.POST, instance=obj)
        friend.save()
        return redirect(to='/hello')
    params = {
        'title': 'Hello',
        'id':num,
        'form': FriendForm(instance=obj),
    }
    return render(request, 'hello/edit.html', params)

def delete(request, num):
    friend = Friend.objects.get(id=num)
    if (request.method == 'POST'):
        friend.delete()
        return redirect(to='/hello')
    params = {
        'title': 'Hello',
        'id':num,
        'obj': friend,
    }
    return render(request, 'hello/delete.html', params)

```

friend_list.htmlを作成
```html:hello/templates/hello/friend_list.html
{% load static %}
<!doctype html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>{{title}}</title>
    <link rel="stylesheet" 
    href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" 
    crossorigin="anonymous">
</head>
<body class="container">
    <h1 class="display-4 text-primary">
        Friends List</h1>
    <table class="table">
        <tr>
            <th>id</th>
            <th>name</th>
            <th></th>
        </tr>
    {% for item in object_list %}
        <tr>
            <th>{{item.id}}</th>
            <td>{{item.name}}</td>
            <td><a href="/hello/detail/{{item.id}}">detail</a></td>
        <tr>
    {% endfor %}
    </table>
</body>

</html>
#http://localhost:8000/hello/listにアクセス
```
![djang1.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1614609/9aeb9619-56ce-56f4-8e29-1af310d49486.png)

friend_detail.htmlを作成
```html:hello/templates/hello/friend_detail.html
{% load static %}
<!doctype html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>{{title}}</title>
    <link rel="stylesheet" 
    href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" 
    crossorigin="anonymous">
</head>
<body class="container">
    <h1 class="display-4 text-primary">
        Friends List</h1>
    <table class="table">
        <tr>
            <th>id</th>
            <th>{{object.id}}</th>
        </tr>
        <tr>
            <th>name</th>
            <td>{{object.name}}</td>
        </tr>
        <tr>
            <th>mail</th>
            <td>{{object.mail}}</td>
        </tr>
        <tr>
            <th>gender</th>
            <td>{{object.gender}}</td>
        </tr>
        <tr>
            <th>age</th>
            <td>{{object.age}}</td>
        </tr>
    </table>
</body>
</html>
#http://localhost:8000/hello/listのdetailをクリック
```
![djang2.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1614609/6e6359c3-61f4-3eb0-da0b-85de7ea71e40.png)

<H1>七日目</H1>
検索ができるようにfind関数をつくる

urls.pyに飛び先を追加
```python:hello/urls.py
from django.urls import path
from . import views
from .views import FriendList
from .views import FriendDetail


urlpatterns = [
    path('', views.index, name='index'),
    path('create', views.create, name='create'),
    path('edit/<int:num>', views.edit, name='edit'),
    path('delete/<int:num>', views.delete, name='delete'),
    path('list', FriendList.as_view()), #☆
    path('detail/<int:pk>', FriendDetail.as_view()), #☆
    path('find', views.find, name='find'), #☆
]
```

find.htmlを作成
```html:hello/templates/hello/find.html
{% load static %}
<!doctype html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>{{title}}</title>
    <link rel="stylesheet" 
    href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" 
    crossorigin="anonymous">
</head>
<body class="container">
    <h1 class="display-4 text-primary">
        {{title}}</h1>
    <p>{{message|safe}}</p>
    <form action="{% url 'find' %}" method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <tr><th></th><td>
        <input type="submit" value="click"
            class="btn btn-primary mt-2"></td></tr>
    </form>
    <hr>
    <table class="table">
        <tr>
            <th>id</th>
            <th>name</th>
            <th>mail</th>
        </tr>
    {% for item in data %}
        <tr>
            <th>{{item.id}}</th>
            <td>{{item.name}}({{item.age}})</td>
            <td>{{item.mail}}</td>
        <tr>
    {% endfor %}
    </table>
</body>
</html>
```

find関数を作成、名前とアドレスで検索
```python:hello/views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import redirect
from .models import Friend
#from .forms import HelloForm
from .forms import FriendForm
from django.views.generic import ListView
from django.views.generic import DetailView
from .forms import FindForm #この文を追記
from django.db.models import Q

class FriendList(ListView):
    model = Friend

class FriendDetail(DetailView):
    model = Friend


def index(request):
    data = Friend.objects.all()
    params = {
        'title': 'Hello',
        'data': data,
    }
    return render(request, 'hello/index.html', params)

# create model
def create(request):
    if (request.method == 'POST'):
        obj = Friend()
        friend = FriendForm(request.POST, instance=obj)
        friend.save()
        return redirect(to='/hello')
    params = {
        'title': 'Hello',
        'form': FriendForm(),
    }
    return render(request, 'hello/create.html', params)

def edit(request, num):
    obj = Friend.objects.get(id=num)
    if (request.method == 'POST'):
        friend = FriendForm(request.POST, instance=obj)
        friend.save()
        return redirect(to='/hello')
    params = {
        'title': 'Hello',
        'id':num,
        'form': FriendForm(instance=obj),
    }
    return render(request, 'hello/edit.html', params)

def delete(request, num):
    friend = Friend.objects.get(id=num)
    if (request.method == 'POST'):
        friend.delete()
        return redirect(to='/hello')
    params = {
        'title': 'Hello',
        'id':num,
        'obj': friend,
    }
    return render(request, 'hello/delete.html', params)

def find(request):
    if (request.method == 'POST'):
        msg = 'search result:'
        form = FindForm(request.POST)
        find = request.POST['find']
        data = Friend.objects.filter(Q(name__contains=find)|Q(mail__contains=find))
    else:
        msg = 'search words...'
        form = FindForm()
        data =Friend.objects.all()
    params = {
        'title': 'Hello',
        'message': msg,
        'form':form,
        'data':data,
    }
    return render(request, 'hello/find.html', params)
#http://localhost:8000/hello/findにアクセス
```
![djang3.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1614609/888aa311-c4fb-abbe-75d0-699c3eb3eba5.png)