I need guidance building a django dropdown
forms.Form field in which I can select multiple choices. I need to select multiple locations on the
office field of the form.
When submitted, the form needs to return a
list of the chosen offices (e.g.
["New York", "Los Angeles"] or
["Austin"]). Returning a
tuple is also acceptable.
The best I can do right now is build a multipleChoiceField for
office with the following:
from django import forms class my_Form(forms.Form): OPTIONS = [ ("0", "*ALL"), ("1", "New York"), ("2", "Los Angeles"), ] office = forms.MultipleChoiceField( choices=OPTIONS, initial='0', widget=forms.SelectMultiple(), required=True, label='Office', )
resulting in this form field layout:
However, I would like this field to be a dropdown, to take up less space on the page.
I found this djangosnippet but (1) a few people have mentioned it appears out of date (I can’t confirm), and (2) I first want to check if a built-in django form/widget setup can fulfill this task before using custom code.
“Dropdown” boxes don’t support multiple selection in HTML; browsers will always render it as a flat box as your image shows.
You probably want to use some kind of JS widget – Select2 is a popular one. There are a couple of Django projects – django-select2, django-easy-select – that aim to make it simple to integrate that into your form; I have no experience with either of them.
(And yes, that snippet – like many things on Djangosnippets – is massively out of date; “newforms” was renamed to “forms” even before version 1.0 of Django.)