I have been trying to use multiple select using django-select2 widget for a while
Step-1: I installed django-select2 using pip install django-select2
Step-2: Added it the installed app
INSTALLED_APPS = [
...
django_select2
...
]
Step-3: I added the below to settings.py
SELECT2_JS = "https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.12/js/select2.min.js"
SELECT2_CSS = "https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.12/css/select2.min.css"
SELECT2_I18N_PATH = "https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.12/js/i18n"
Step 4: I tried it using the widgets
from django_select2.forms import Select2MultipleWidget
class ClientForm(AppModelForm):
class Meta:
model = Client
fields = "__all__"
exclude = ['client_website']
widgets = {
'point_of_contact': Select2MultipleWidget
}
Step 5: Just render the form without any loop of any sort
{{ client_form }}
The result is
No style is applied to the select.
I also tried including the styles and scripts in the head tag (Didn't help).
I belive the widget is working, because when i switch from Select2MultipleWidget
to Select2Widget
, It changes to a single select
<select name="point_of_contact" lang="None" data-minimum-input-length="0" data-theme="default" data-allow-clear="true" data-placeholder="" id="id_point_of_contact" class="django-select2" multiple="">
<option value="2">Test</option>
<option value="1">Tester</option>
</select>
The above is the html rendered for the multi select widget by django
Kindly help in getting the functionality of django-select2
By default SELECT2_JS
and SELECT2_CSS
points to the respective Cloudflare CDN. Use it when you want to load a specific version from CDN or when you want to load from local storage.
Make sure to add select2 url patterns to the main urls.py:
urlpatterns = [
path("select2/", include("django_select2.urls")),
# other patterns
]
and add form assets in template file:
<!-- To render stylesheet link tags of select2 -->
{{ client_form.media.css }}
<form method="POST">
{% csrf_token %}
{{ client_form }}
<input type="submit">
</form>
<!-- Add JQuery script -->
<!-- To render script tags of select2 -->
{{ client_form.media.js }}
Installation and Quick start guides are available here:
https://django-select2.readthedocs.io/en/latest/#installation
https://django-select2.readthedocs.io/en/latest/#quick-start
Django Form Assets: https://docs.djangoproject.com/en/3.2/topics/forms/media/