フォームクラスを使ってフォーム送信をしていきます。
フォームクラスの作成
まずは、アプリケーションのフォルダ直下に、
forms.pyを作り、下記のようにフォームクラスを作ります。
from django import forms
class testForm(forms.Form):
id = forms.IntegerField()
name = forms.CharField()
フォームクラスを使ってフォーム送信
まずはビューの解説です。
indexメソッドでは、フォームクラスのインスタンスを作り、テンプレートに送っています。
resultメソッドは、テンプレートから送られたデータを受け取り、その結果を別のテンプレートで画面表示しています。
views.py
from django.http import HttpResponse
from django.shortcuts import render
from testapp.forms import testForm
def index(request):
test_form = testForm()
return render(request, 'index.html', {'test_form':test_form})
def result(request):
# フォーム送信された値を受け取る
result_id = request.POST.get('id')
result_num = request.POST.get('name')
return render(request, 'result.html', {'id': result_id,'name': result_num})
テンプレート側
フォームクラスを使って、
入力フォームをテンプレートで作ります。
index.html
<!DOCTYPE html>
<html>
<head>
<title>タイトル</title>
</head>
<body>
{% with test_form as form %}
<form action="{% url 'testapp:result' %}" method="post">
{% csrf_token %}
<div>ID:{{form.id}}</div>
<div>名前:{{form.name}}</div>
<input type="submit" value="送信">
</form>
{% endwith %}
</body>
</html>
そして、結果表示用のテンプレートを作ります。
result.html
結果
ID:{{id}}
名前:{{name}}
実行結果
index.html

result.html

フォームクラスを使ってフォーム送信することができました。
