While attempting to implement Django Autocomplete Light within my Django admin, I encountered the following error:
select2.full.js:491 Select2: An instance of jQuery or a jQuery-compatible library was not found. Make sure that you are including jQuery before Select2 on your web page.
The *reason* for the issue was pretty apparent: Django’s jquery.init.js library transforms the jQuery namespace into django.jQuery, and thus autocomplete libraries are unable to initialize properly.
Most pages suggested running Django’s collectstatic command, and ensuring dal and dal_select2 were loaded above django.contrib.admin in the settings file:
INSTALLED_APPS = [ 'dal', 'dal_select2', 'django.contrib.admin', ]
As my settings were configured properly, collectstatic didn’t resolve the issue, and there did not seem to be a way to manually rearrange the library loading order, I opted for a simple (perhaps less-than-ideal-but-gets-the-job-done) resolution: include jQuery a second time on that page by defining it within the Meta js property of the admin.ModelAdmin object:
class PersonAdmin(admin.ModelAdmin): form = PersonForm class Media: js = ( 'admin/js/vendor/jquery/jquery.min.js', )
However that only gets us halfway there as I then encountered the following exception:
jquery.min.js:2 Uncaught TypeError: $(…).select2 is not a function
Basically the autocomplete libraries still need to be initialized with the new jQuery namespace. I re-included the autocomplete jQuery init library, and to tidy things up even more, I created an abstract AutocompleteAdmin object to inherit from:
class AutocompleteAdmin(admin.ModelAdmin): class Media: abstract = True js = ( 'admin/js/vendor/jquery/jquery.min.js', 'autocomplete_light/jquery.init.js', ) class PersonAdmin(AutocompleteAdmin): form = PersonForm class PlaceAdmin(AutocompleteAdmin): form PlaceForm
After that, autocomplete works like a charm! Hope that helps someone out there!