[Fixed]-Django – dropdown form with multiple select

18πŸ‘

βœ…

"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.)

4πŸ‘

You can choose multiple choices by using Django select2. Include below code in your respective HTML file.

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>

<select class="select_field_class" multiple="multiple" name="option" id="option">
      <option value="">Enter the option</option>
      {% for option in options %}
         <option value="{{ option.id }}">{{ option.name }}</option>
      {% endfor %}
</select>

$('.select_field_class').select2( { placeholder: "Select here", maximumSelectionSize: 100  } );
πŸ‘€MicroPyramid

2πŸ‘

This is late but hope it helps someone else.

You can also do it a combination of django forms and a select2 widget Select2MultipleWidget to make it look cleaner.

class YourCreateForm(forms.ModelForm):
     CHOICES = (("address1","address1"), ("address2","address2"))
     address=forms.MultipleChoiceField(choices=CHOICES,widget=Select2MultipleWidget)

     class Meta:
         model = YourModel
         fields = ("field1","address",)

Do not forget to install and import the django select2 widgets

πŸ‘€Codebender

1πŸ‘

As I said in a similar question, one suggestion is use Bootstrap with Python.

forms.py

(...)
class yourForm(forms.Form):
    options = forms.MultipleChoiceField(
    choices=OPTIONS, widget=forms.CheckboxSelectMultiple(),
    label="myLabel", required=True, error_messages={'required': 'myRequiredMessage'})

view.py

def anything(...):
    (...)
    form = yourForm( )
    (...)
    return render(request, "myPage.html", {'form': form})

myPage.html

(...)
{% csrf_token %}
    {% for field in form %}
        <div class="col-md-12 dropdown">
            <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">{{ field.label_tag }}
                <span class="caret"></span>
            </button>
            <div class="dropdown-menu">
                <div><a href="#">{{ field }}</a></div>
            </div>
        </div>
    {% endfor %}
(...)
πŸ‘€Davidson Lima

Leave a comment