Django - dropdown form with multiple select
<p><strong>I need guidance building a django <em>dropdown</em> <code>forms.Form</code> field in which I can select <em>multiple</em> choices.  I need to select multiple locations on the <code>office</code> field of the form.</strong></p>

<p>When submitted, the form needs to return a <code>list</code> of the chosen offices (e.g. <code>["New York", "Los Angeles"]</code> or <code>["Austin"]</code>).  Returning a <code>tuple</code> is also acceptable.</p>

<hr>

<p>The best I can do right now is build a <a href="https://docs.djangoproject.com/en/1.10/ref/forms/fields/#multiplechoicefield" rel="nofollow">multipleChoiceField</a> for <code>office</code> with the following:</p>

<pre><code>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',
        )
</code></pre>

<p>resulting in this form field layout:</p>

<p><a href="http://i.stack.imgur.com/7OZIH.png" rel="nofollow"><img src="http://i.stack.imgur.com/7OZIH.png" alt="enter image description here"></a></p>

<hr>

<p>However, I would like this field to be a dropdown, to take up less space on the page.</p>

<p>I found this <a href="https://djangosnippets.org/snippets/747/" rel="nofollow">djangosnippet</a> 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.</p>

<p>"Dropdown" boxes don't support multiple selection in HTML; browsers will always render it as a flat box as your image shows.</p>

<p>You probably want to use some kind of JS widget - <a href="https://select2.github.io/" rel="nofollow">Select2</a> is a popular one. There are a couple of Django projects - <a href="https://github.com/applegrew/django-select2" rel="nofollow">django-select2</a>, <a href="https://github.com/asyncee/django-easy-select2" rel="nofollow">django-easy-select</a> - that aim to make it simple to integrate that into your form; I have no experience with either of them.</p>

<p>(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.)</p>

python django forms