[Django]formモジュール1

## formモジュール
### CharField
– input type=”text”を生成
– requred, min_length, max_length

### EmailField
– input type=”emailを生成

### IntegerField, FloatField
– input type=”number”を生成

### URLField
– input type=”url”

### 日時に関するフィールド
– DateField, TimeField, DateTimeField

### BooleanField
/hello/forms.py

class HelloForm(forms.Form):
	check = forms.BooleanField(label='Checkbox', required=False)

/hello/templates/hello/index.html

<h1 class="display-4 text-primary">{{title}}</h1>
	<p class="h5 mt-4">{{result|safe}}</p>
	<form action="{% url 'index' %}" method="post">
		{% csrf_token %}
		<table>
			{{ form.as_p }}
			<tr>
				<td></td>
				<td><input class="btn btn-primary my-2" type="submit" value="click"></td>
			</tr>
		</table>
	</form>

/hello/views.py

class HelloView(TemplateView):

	def __init__(self):
		self.params = {
			'title': 'Hello',
			'form': HelloForm(),
			'result': None
		}

	def get(self, request):
		return render(request, 'hello/index.html', self.params)

	def post(self, request):
		if('check' in request.POST):
			self.params['result'] = 'Checked!!'
		else:
			self.params['result'] = 'not checked...'
		self.params['form'] = HelloForm(request.POST)
		return render(request, 'hello/index.html', self.params)

### NullBooleanField
– Yes, No, Unknownの項目を持つメニュー

class HelloForm(forms.Form):
	check = forms.NullBooleanField(label='Checkbox')
	def post(self, request):
		chk = request.POST['check']
		self.params['result'] = 'you selected: "' + chk + '".'
		self.params['form'] = HelloForm(request.POST)
		return render(request, 'hello/index.html', self.params)

[Django]ビュー関数をクラス化

– TemplateViewクラスを継承して定義する
– TemplateViewクラスはViewクラスの派生クラス

class クラス名 (TemplateView)
	
	def get(self, request):
		...GET時の処理...

	def post(self, request):
		...GET時の処理...

### HelloViewクラス
/hello/views.py

from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import TemplateView
from .forms import HelloForm

class HelloView(TemplateView):

	def __init__(self):
		self.params = {
			'title': 'Hello',
			'message': 'your data:',
			'form': HelloForm()
		}

	def get(self, request):
		return render(request, 'hello/index.html', self.params)

	def post(self, request):
		msg = 'あなたは、<b>' + request.POST['name'] + \
			'(' + request.POST['age'] + \
			')</b>さんです。<br>メールアドレスは<b>' + request.POST['mail'] + \
			'</b>ですね。'
		self.params['message'] = msg
		self.params['form'] = HelloForm(request.POST)
		return render(request, 'hello/index.html', self.params)

– __init__は初期化メソッド

/hello/urls.py

from django.conf.urls import url
from .views import HelloView

urlpatterns = [ 
	url(r'', HelloView.as_view(), name='index'),
]

フォームは関数で書くよりもクラス推奨のようです。

[Django]フィールドをタグで整形

Djangoのフォームクラスには出力機能が備えられている
– form.as_table
– form.as_p
– form.as_ul

<form action="{% url 'index' %}" method="post">
		{% csrf_token %}
		<table>
		{{ form.as_table }}
			<tr>
				<td></td>
				<td><input class="btn btn-primary" type="submit" value="click"></td>
			</tr>
		</table>
	</form>

– form.as_tableだけだとtr, tdタグしか出力されない為、tableタグを用意する必要がある

## Bootstrapクラス
### forms.py
/hello/forms.py

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'}))

– TextInputはformsはinput type=”text”
– NumberInputはformsはinput type=”number”

### index.html
/hello/templates/hello/index.html

<form action="{% url 'index' %}" method="post">
		{% csrf_token %}
		{{ form.as_table }}
		<input class="btn btn-primary my-2" type="submit" value="click">
	</form>

attributeは絶対に実装するので、このwidgetの書き方は必須です。

[Django]フォーム機能

### フォームクラス
Djangoに予め用意されているフォームクラスを使う
– アプリケーションフォルダ内にforms.pyを作成する

/hello/forms.py

from django import forms

class HelloForm(forms.Form):
	name = forms.CharField(label='name')
	mail = forms.CharField(label='mail')
	age = forms.IntegerField(label='age')

– Formクラスはform.Formというクラスを継承している
– クラス内には用意するフィールドを変数として用意する
– forms.CharFieldはテキスト、forms.IntegerFieldは整数値

### views.py
/hello/views.py

from django.shortcuts import render
from django.http import HttpResponse
from .forms import HelloForm

def index(request):
	params = {
		'title':'Hello',
		'message':'your data',
		'form': HelloForm(),
	}
	if (request.method == 'POST'):
		params['message'] = 'name: ' + request.POST['name'] + \
			"<br>mail: " + request.POST['mail'] + \
			"<br>age: " + request.POST['age']
		params['form'] = HelloForm(request.POST)
	return render(request, 'hello/index.html', params)

– 初期値は’form’: HelloForm()とし、送信後はparams[‘form’] = HelloForm(request.POST)として上書きしている

### index.html
/hello/templates/hello/index.html

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>{{title}}</title>
	<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" crossoorigin="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 }}
		<input class="btn btn-primary" type="submit" value="click">
	</form>
</body>
</html>

– formの具体的内容は既に作成済の為、{{ form }}のみ記載
– {{messsage|safe}}はエスケープ処理なし

### urls.py
/hello/urls.py

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

[Django]フォームの送信

### index.html
/hello/templates/hello/index.html

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>{{title}}</title>
	<link rel="stylesheet" type="text/css" href="{% static 'hello/css/styles.css' %}">
</head>
<body>
	<h1>{{title}}</h1>
	<p>{{msg}}</p>
	<form action="{% url 'form' %}" method="post">
		{% csrf_token %}
		<label for="msg">message: </label>
		<input id="msg" type="text" name="msg">
		<input type="submit" value="click">
	</form>
</body>
</html>

– urls.pyにnameの’form’を追加する
– {% csrf_token %}はCSRF対策

### views.py
/hello/views.py

def index(request):
	params = {
		'title':'Hello/Index',
		'msg':'what is your name?',
		'goto':'next',
	}
	return render(request, 'hello/index.html', params)

def form(request):
	msg = request.POST['msg']
	params = {
		'title':'Hello/Form',
		'msg':'hello ' + msg + '!',
	}
	return render(request, 'hello/index.html', params)

### urls.py
/hello/urls.py

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

### Bootstrap
– bootstrapを使ったデザイン

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>{{title}}</title>
	<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" crossoorigin="anonymous">
</head>
<body class="container">
	<h1 class="display-4 text-primary">{{title}}</h1>
	<p class="h5 mt-4">{{msg}}</p>
	<form action="{% url 'form' %}" method="post">
		{% csrf_token %}
		<div class="form-group">
			<label for="msg">message: </label>
			<input id="msg" type="text" class="form-control" name="msg">
		</div>
		<input class="btn btn-primary" type="submit" value="click">
	</form>
</body>
</html>

ほう

[Django]静的ファイルの利用

### staticフォルダ
– 静的ファイルは各アプリケーションのstaticフォルダに配置する
– ここではstatic, hello, cssフォルダ配下にcssファイルを作成する

/hello/static/hello/css/styles.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;
}

### index.html
/hello/templates/hello/index.html

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>{{title}}</title>
	<link rel="stylesheet" type="text/css" href="{% static 'hello/css/styles.css' %}">
</head>
<body>
	<h1>{{title}}</h1>
	<p>{{msg}}</p>
	<p><a href="{% url goto %}">{{goto}}</a></p>
</body>
</html>

– 静的ファイルをロードする際にはテンプレートファイルで{% load static %}と書く
– staticファイルの読み込みは{% static ‘hello/css/styles.css’ %}と書く

なんじゃこりゃ

[Django]複数ページの移動

### テンプレート側
/hello/templates/hello/index.html

<body>
	<h1>{{title}}</h1>
	<p>{{msg}}</p>
	<p><a href="{% url goto %}">{{goto}}</a></p>
</body>
</html>

– {% %}はテンプレートタグ
– {% url ${name} %}で、urls.pyで指定しているnameのパスに遷移する

### views.py
/hello/views.py

def index(request):
	params = {
		'title':'Hello/Index',
		'msg':'this is sample page.',
		'goto':'next',
	}
	return render(request, 'hello/index.html', params)

def next(request):
	params = {
		'title':'Hello/Index',
		'msg':'this is another page.',
		'goto':'index',
	}
	return render(request, 'hello/index.html', params)

### urls.py
/hello/urls.py

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

http://192.168.33.10:8000/hello/

http://192.168.33.10:8000/hello/next

{% %}のテンプレートタグがやや特殊な動きをします。

[Django]テンプレートに値を渡す

### テンプレート側
/hello/templates/hello/index.html

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>{{title}}</title>
</head>
<body>
	<h1>{{title}}</h1>
	<p>{{msg}}</p>
</body>
</html>

### views.pyの修正
/hello/views.py

def index(request):
	params = {
		'title':'Hello/Index',
		'msg':'this is sample page.',
	}
	return render(request, 'hello/index.html', params)

paramsはkeyとvalueのdictionary

[Django]テンプレートの利用

### アプリケーションの登録
– プロジェクトフォルダのsettings.pyにアプリケーションを登録する
– INSTALLED_APPSに登録してtemplatesフォルダを検索できるようにする
/django_app/settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'hello', # 追加
]

### テンプレートフォルダの作成
/django_app/hello/templates/hello
– 他のアプリケーションと間違わないように、templatesの下にアプリケーション名のフォルダを作成する

### index.htmlを作成
/hello/templates/hello/index.html

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>hello</title>
</head>
<body>
	<h1>hello/index</h1>
	<p>This is sample page.</p>
</body>
</html>

/hello/urls.py

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

/hello/views.py

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

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

– render はテンプレートをレンダリングするのに使われる

http://192.168.33.10:8000/hello/

ほう、少し楽しくなってきました。

[Django]クエリパラメータを使用する

### クエリパラメータを記述する
クエリパラメータとはアドレスの後につけて記述するパラメータの事
e.g. http://hoge.com/hello/index?xxx=yyyy&zzz=aaa… など

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

def index(request):
	msg = request.GET['msg']
	return HttpResponse('you typed : "' + msg +'".')

– request.GET[‘&{param}’]でGETパラメータを取り出す。
– リクエストはHttpRequestクラスを使用し、レスポンスはHttpResponseクラスを使用する

### クエリパラメータがない時
MultiValueDictKeyErrorになるので、views.pyでmsgがない時の処理を追加する

/hello/views.py

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

def index(request):
	if 'msg' in request.GET:
		msg = request.GET['msg']
		result = 'you typed : "' + msg +'".'
	else:
		result = 'please send msg parameter!'
	return HttpResponse(result)

– GETプロパティに設定されている値はQueryDictというクラスのインスタンス

### クエリパラメーターをスラッシュ(“/”)に変更する
/hello/urls.py

urlpatterns = [ 
	path('<int:id>/<nickname>', views.index, name='index'),
]

/hello/views.py

def index(request, id, nickname):
	result = 'your id: ' + str(id) + ', name: "' \
		+ nickname + '".'
	return HttpResponse(result)

– 文末のバックスラッシュ(“\”)は見かけの改行