Answer the question
In order to leave comments, you need to log in
How to create Multiple Select Box in Django?
Hello!
Please help me figure it out. I'm trying to use the Django Select 2 library , or rather I'm trying to create a Multiple Select Box like in the picture below. The field itself must store objects from the queryset. I tried to use the following code, but as a result I displayed a standard select multiple widget. What did I miss?
django-select-2 version: 5.1.0
jQuery version: 3.1.1
forms.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
{% 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 %}
$(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);
});
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question