How to create a Multiple Select Box in Django?

Hello!

Please help to understand. Trying to use the Django Select 2, but rather trying to create a field Multiple Select Box as in the picture below. The field itself needs to store objects from a queryset. Tried to use the following code, but the result brought the standard multiple select widget. What did I miss?

django-select-2 version: 5.1.0
JQuery version: 3.1.1


select2.gifforms.py:
class ProductForm(forms.ModelForm):
 company = forms.ModelMultipleChoiceField(queryset=company.objects.none())

 class Meta:
 model = Product
 fields = ('company ',)
 widgets = {
 'company': Select2MultipleWidget()
}

 def __init__(self, all_companies, *args, **kwargs):
 super(ProductForm, self).__init__(*args, **kwargs)
 self.fields['company'].queryset = all_companies


template:
{% block style %}
 {{ product_form.media.css }}
{% endblock %}

{% load widget_tweaks %}

<form method="post" action>
 {% csrf_token %}
 <div class="modal-body">
 {% for field in product_form %}
 <div class="form-group{% if field.errors %} has-danger{% endif %}">
 <label class="form-control-label" for="{{ field.id_for_label }}">{{ field.label }}</label>

 {% render_field field class="form-control" %}

 {% for error in field.errors %}
 <div class="form-control-feedback">{{ error }}</div>
 {% endfor %}
</div>
 {% endfor %}
</div>
 <div class="modal-footer">
 <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
 <button type="submit" class="btn btn-primary">Create</button>
</div>
</form>

{% block script %}
 {{ product_form.media.js }}
{% endblock %}


JS:
$(function () {
 var loadForm = function () {
 var btn = $(this);
$.ajax({
 url: btn.attr("data-url"),
 type: 'get',
 dataType: 'json',
 beforeSend: function () {
 $('#id_company').djangoSelect2({multiple: true});
$("#modal").modal("show");
},
 success: function (data) {
 $("#modal .modal-content").html(data.html_product_form);
}
});
};

$("#product-add-button").click(loadForm);
});
June 26th 19 at 14:15
0 answer

Find more questions by tags DjangoPython