Search code examples
javascriptjquery-select2-4django-2.1

Select2 4.0.5 common errors in Django admin


(Disclaimer: this is a self-answered question)

I wanted to set up some Select2 to my form fields while in a Django admin panel (specifically in the change_list.html template). So I added the neccesary scripts to the page (not the full version), but when it loads, I get this errors:

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.
TypeError: a is undefined
TypeError: e is undefined
TypeError: $ is not a function

And when you search for one of those errors (well, not the first and last ones), the answers aren't on the same subject (normally it has to do with a bad processResults setup, or problems with Bootstrap) or in the docs neither.

How can I fix it?


Solution

  • There are two steps involved fixing it:

    Setting a var called $

    This one is the first thing you think of when you see the last line (TypeError: $ is not a function), and all scripts normally use it (who doesn't uses $ in their scripts?). But when you modify it, you still get these errors:

    TypeError: a is undefined
    TypeError: e is undefined
    

    So, we have to go deeper...

    Setting a var called jQuery

    This one can be a little hidden, as we have to dig into the select2.js script (you normally use the minified version, so only $ is showed instead).

    Looks like a var called jQuery is used sometimes, so you also have to set it up in your JS.

    How the fix should look like

    Add this script before your Select2 scripts:

    <script type="text/javascript">
        // To prevent errors for Select2 JS
        var $ = django.jQuery;
        var jQuery = django.jQuery;
    </script>