django-select2 in Django
Jan. 10, 2019, 2:48 a.m.
Deprecated!
It is actual for django-select2 <= 7.7.1
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
from django_select2.forms import Select2Widget as BaseSelect2Widget class Select2Widget(BaseSelect2Widget): """ Added jquery to widget """ def _get_media(self): media = super()._get_media() css = ['select2/css/select2.css'] # if you want override some styles css.extend(media._css['screen']) extra = '' if settings.DEBUG else '.min' js = [f'admin/js/vendor/jquery/jquery{extra}.js', 'admin/js/jquery.init.js', 'my_app/admin_compat.js'] js.extend(media._js) return forms.Media(js=js, css={'screen': css}) media = property(_get_media)
if (window.django !== undefined) var jQuery = django.jQuery, $ = django.jQuery;
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.
Comments: 0