Djangoでプルダウンなどを作成するときにChoiceFieldが使えるのですが、 POSTされてきた値の取得方法がやや特殊?だったのでメモです。
ちなみにChoiceFieldは正確には以下。
django.forms.fields.ChoiceField
サンプルフォーム作成
以下をサンプルとして定義します。 だいたい、みなさんアプリケーション内のforms.pyとかに書いてるはず。。
- forms.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django import forms | |
class SampleChoiceForm(forms.Form): | |
CHOICE = ( | |
('hoge', 'ほげほげ'), | |
('huga', 'ふが'), | |
) | |
select = forms.fields.ChoiceField(required=True, widget=forms.widgets.Select, choices=CHOICE) |
テンプレートに表示
一応プルダウンをテンプレートに表示する部分も記載。
- views.py + 表示するhtml
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.shortcuts import render | |
from app.forms import SampleChoiceForm | |
def choice_sample(request): | |
choice = SampleChoiceForm() | |
return render(request, | |
'app/sample.html', # 表示するhtml | |
{ | |
'choice': choice, | |
} | |
) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<form method="POST" action="{% url 'app:movie_sort' %}"> | |
{% for field in choice %} | |
{{ field }} | |
{% endfor %} | |
{% csrf_token %} | |
<button type="submit" class="btn btn-outline-info">SUBMIT</button> | |
</form> |
データを受け取る
views.pyに追記しています。
- views.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.shortcuts import render | |
from app.forms import SampleChoiceForm | |
def choice_sample(request): | |
choice = SampleChoiceForm() | |
return render(request, | |
'app/sample.html', # 表示するhtml | |
{ | |
'choice': choice, | |
} | |
) | |
# 追加部分 | |
def choice_sample_submitted(request): | |
if request.method == 'POST': | |
form = SampleChoiceForm(request.POST) | |
if form.is_valid(): | |
# cleaned_data['SampleChoiceFormのプロパティ名'] | |
print(form.cleaned_data['select']) | |
return HttpResponse('SUBMIT!') |
form = SampleChoiceForm(request.POST)でフォームのインスタンスを作った後に form.cleaned_data['SampleChoiceFormのプロパティ名']で取得する