问题
I am tring to create Multiple Select Box field from Django Select 2 library as in the picture below? I used next code but it return simple select multiple widget. I think I forgot something to add. Where is my mistake? Can someone show me how create such field correctly?
I use:
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
template:
{% block style %}
{{ 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 %}
{{ 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);
});
回答1:
Here's an idea. I think you need to initialize it yourself with the jquery plugin provided by Django-Select2. Following the Django-Select2 docs and the Select2 docs, you might need to do the following:
$('.django-select2').djangoSelect2({multiple: true});
回答2:
Finally I found solution. My problem was that I load my form by AJAX. For thats why {{ product_form.media.js }}
and {{ product_form.media.css }}
didnt work.
Instead of {{ product_form.media.js }}
and {{ product_form.media.css }}
I use this in my template:
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css">
<script src="{% static 'django_select2/django_select2.js' %}"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
来源:https://stackoverflow.com/questions/43917791/how-create-multiple-select-box-in-django