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
pip install django_select2
Add package in
INSTALLED_APPS = ( ... 'django_select2', )
If you use
ModelWidgets, add urls:
2. Create own custom widget based on Select2Widget
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:
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.