django-select2 in Django

Jan. 9, 2019, 9:48 p.m.

Immediately use django_select2 in the Django admin does not work because django_select2 requires jQuery. By default django_select2 widget does not include jQuery. You can read more about this on Add jquery to widget Django.

To quickly add jQuery to django_select2, do the following:

1. Add django-select2

Install django_select2:

pip install django_select2

Add package in ISTALLED_APPS:

INSTALLED_APPS = (
    ...
    'django_select2',
)

If you use ModelWidgets, add urls:

url(r'^select2/', include('django_select2.urls')),

2. Create own custom widget based on Select2Widget

my_app/widgets.py
from django_select2.forms import Select2Widget as BaseSelect2Widget

class Select2Widget(BaseSelect2Widget):
    """
    Added jquery to widget
    """
    def _get_media(self):
        media = super(Select2Widget, self)._get_media()
       
        extra = '' if settings.DEBUG else '.min'
        js = ['vendor/jquery/jquery%s.js' % extra, 'jquery.init.js']
        js = ['admin/js/%s' % url for url in js]
        js.append('my_app/admin_compat.js')

        # insert scripts before Select2Widget scripts
        for i, url in enumerate(js):
            media._js.insert(i, url)

        return media

    media = property(_get_media)

3. Use custom widget in your code:

my_app/forms.py
from my_app.widgets import Select2Widget

class MyForm(forms.Form):
   my_choice = forms.ChoiceField(widget=Select2Widget)

Now it should works.

In the second step, the jQuery version was used, which is part of Django. but you can use your version of jQuery. How to do this and other settings, you can read on the page Add jquery to widget Django.

Rate this article

0 from 5 (total 0 ratings)

You can send feedback, suggestions or comments on this article using this form:

Fields marked by star ( * ) is required.

Thank you for yor feedback!

After clicking the "Send" button, your message will be delivered to me on the mail.

Author of Article

The right to use content on this page https://vivazzi.pro/en/it/django-select2-django/:

Permission is granted to copy an content with its author and reference to the original without using the parameter rel="nofollow" in tag <a>. Usage:

Author of Article: Maltsev Artem
Link to article: <a href="https://vivazzi.pro/en/it/django-select2-django/">https://vivazzi.pro/en/it/django-select2-django/</a>

More: Terms of site usage

Comments: 0

You can leave a comment as an unregistered user.

But if you sing up, you can:

  • receive notifications
  • view your comments
  • be able to use all the functions of the developed services

To comment in one's own name you should log in or sign up in the usual way or through social networks:

Send

There is no search on this site, so I offer to use usual search engine, for example, Google, adding "vivazzi" after your request.

Try it