4

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

enter image description here

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);
});
Nurzhan Nogerbek
  • 4,806
  • 16
  • 87
  • 193
  • What does your template look like? Do you include the javascript needed by the form as shown in [this](https://github.com/applegrew/django-select2/blob/master/tests/testapp/templates/form.html#L24) example? – ikkuh May 11 '17 at 14:18
  • Hello! I add my current template to post. It seems like I didnt add js to my form. Can you show me what exactly I need to add. This: `{{ form.media.js }}`? – Nurzhan Nogerbek May 11 '17 at 14:26
  • Yes, I you should add `{{form.media.js}}` somewhere at the bottom of your template. Haven't really used the django library, but select2 needs to run some javascript in order to convert select elements. – ikkuh May 11 '17 at 16:12
  • I add `{{ form.media.css }}` and `{{ form.media.js }}` but it didnt help. So sad. Do you have any other ideas my friend?) – Nurzhan Nogerbek May 11 '17 at 17:01

2 Answers2

2

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});
  • Hello! I tried it also but it didnt help for me. I used this: `$('#id_company').djangoSelect2();`. `id_company` is id of select element. I add html of select element which was generated by Django to my post. Do you have any ideas my friend? – Nurzhan Nogerbek May 12 '17 at 02:23
  • I use 3 vertion of JQuery. This can affect to the result? – Nurzhan Nogerbek May 12 '17 at 04:05
  • Did you use `{multiple : true}`? – Dibya Chakravorty May 12 '17 at 07:01
  • Yes, I did. I used this also: `$('#id_company').djangoSelect2({multiple: true});` – Nurzhan Nogerbek May 12 '17 at 08:56
  • Try true in quotes maybe ? `multiple : "true"` . If this doesn't work as well, can you open the debugger in your browser and check if there are any error messages? – Dibya Chakravorty May 12 '17 at 10:57
  • In browser console I have this error: `Uncaught TypeError: $(...).djangoSelect2 is not a function at 127.0.0.1/:131` What do think about that? – Nurzhan Nogerbek May 12 '17 at 11:07
  • It seems like the javascript which is [here](https://github.com/applegrew/django-select2/blob/master/django_select2/static/django_select2/django_select2.js) is not loaded, but I am not sure. Did you add `{{ form.media.js }}` before doing `$('#id_company').djangoSelect2({multiple: "true"});` ? – Dibya Chakravorty May 12 '17 at 12:35
  • I add `{{ form.media.js }}` in my template but then check html in browser and notice that the place where I put `{{ form.media.js }}` is empty. I am so comfused. =( – Nurzhan Nogerbek May 12 '17 at 14:01
  • You know I forget to say that my form inside modal window and I load form by AJAX. I did an experiment and add form outside of modal window. I notice that outside `Select2MultipleWidget` works. My form must be inside modal so how to fix this problem now? Do you have any ideas? I add js/ajax code which load form to post. Check it pls. – Nurzhan Nogerbek May 12 '17 at 16:36
  • I put `$('#id_company').djangoSelect2({multiple: true});` in my `AJAX code`? `Look beforeSend` in ajax code in post pls. I notice that in html the places where I declare `{{ product_form.media.js }}` and `{{ product_form.media.css }}` are empty. Also instead of them I tried to put next links but anyway there is no `Select2MultipleWidget`. Can you show me what exactly I need to change? `` and `` – Nurzhan Nogerbek May 13 '17 at 05:22
0

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>
Nurzhan Nogerbek
  • 4,806
  • 16
  • 87
  • 193