一日目
djangoのインストールpip install Django==3.0.4
//バージョン指定はしなくてもいい
プロジェクトの作成
django-admin startproject django_app
//django_appとゆうプロジェクト作成
サーバーの起動
cd django_app
python manage.py runserver
//ブラウザでhttp://localhost:8000
二日目
アプリケーションの作成python manage.py startapp hello
//helloとゆうフォルダが作成される
view.pyを編集する
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello Django!!")
hello/urls.pyを作成、編集する
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'), #indexとゆう名前を付与
]
プロジェクト直下/urls.pyを編集する
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をブラウザで確認
urlのクエリパラメーターを利用するhello/urls.pyとhello/view.pyを編集する
from django.urls import path
from . import views
urlpatterns = [
path('<int:id>/<nickname>/', views.index, name='index'),
#基本文字列なのでintを指定
]
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をブラウザで確認
三日目
templatesをつかう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関数の修正
<!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>
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return render(request, '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>
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)
複数ページの移動
<!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>
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)
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('next', views.next, name='next'),
]
cssを使う、静的ファイルの管理、
staticフォルダの作成、bootstrapの使い方
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;
}
{% 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>
四日目
formをつかう, 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での編集をなくしている
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の表示を分けている
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
#indexだけで処理しているため
{% 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>
五日目
モデルとデータベース Friendモデルクラスの作成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) +')>'
マイグレーションファイルの作成
python manage.py makemigrations hello
マイグレーションファイルの実行
python manage.py migrate
管理ツールの作成
python manage.py createsuperuser
admin.pyにFriendモデルを追加
from django.contrib import admin
from .models import Friend
admin.site.register(Friend)
#http://localhost:8000/adminにアクセス
モデルのobjectはmanagerクラスでできている、
QuerySetを使ってデータベースの中身を取り出し編集する。
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
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)
{% 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>
六日目
ModelFormでDRUDを作成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にクラスを追加
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関数を作成
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を作成
{% 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にアクセス
edit関数をつくる
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を修正
{% 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を作成
{% 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をクリック
delete関数をつくる
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を修正
{% 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を作成
{% 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をクリック
ジェネリックビューの作成
views.pyにimportとクラスを追加
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を作成
{% 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にアクセス
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をクリック
七日目
検索ができるようにfind関数をつくる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を作成
{% 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関数を作成、名前とアドレスで検索
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にアクセス