htmlで作成したフォームは一度送信するとフォーム内容がクリアされてしまう問題があります。
そこで、DjangoのFormクラスを使用します。
Formというクラスを作成して、そこでフォームの内容を定義しておきます。
まずは、forms.pyを作成します。
「django_app」→「hello」→「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')
ビュー関数を作成します。
hello/views.py
from django.shortcuts import render
from .forms import HelloForm
def index(request):
params = {
'title': 'Hello',
'message': '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)
HelloFormを表示させるため、index.htmlを修正します。
hello/templates/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" class="btn btn-primary">
</form>
</body>
最後にurlspatternsを修正します。
urlpatterns = [
path('', views.index, name='index'),
]
webブラウザにてアクセスします。name、mail、ageにそれぞれ入力して「click」をクリックします。



フォームが横一列で見ずらいので縦に並べ替えます。
htmlをタグにて整えます。
hello/templates/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 %}
<table>
{{ form.as_table }}
<tr><td></td><td>
<input type="submit" value="click" class="btn btn-primary">
</td></tr>
</table>
</form>
</body>
webブラウザにてアクセスします。

また、Bootstraoクラスを使用してフォームを表示させるには、forms.pyのHelloFormクラスを修正します。
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'}))
index.htmlの<form>タグを書き換えます。
/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.as_p }}
<input type="submit" class="btn btn-primary my-2"
value="click">
</form>
</body>
webブラウザにてアクセスします。


この記事は役に立ちましたか?
もし参考になりましたら、下記のボタンで教えてください。
コメント