[Fixed]-Django.jQuery $ is not a function message

4👍

Use the class Media in your admin.py file like this:

class Media:
    js = (
        '//ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js',  # jquery
        'js/admin.js',       # project static folder
    )
👤AleMal

44👍

Instead of adding second copy of jQuery just make sure your JS is executed after djagno.jQuery is defined.

You can solve this issue by simply wrapping your JS in with an event listener that fires when the window has loaded.

window.addEventListener("load", function() {
    (function($) {
        $("select[name='main_id']").change(function() {
            $("select['test_id']").val('');
        });
    })(django.jQuery);
});

The "load" event is fired when the window, as you might have guessed, loads. window.addEventListener() simply registers an event listener that executes the contents of the anonymous function when the event fires. This happens after all resources have loaded.

Because the window "load" event will fire after $(document).ready() you don’t need that anymore.

2👍

Let’s try to insert jQuery script before?

{{ block.super }}
    <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous" defer></script>
    <script type="text/javascript" src="{% static 'js/admin.js' %}" defer></script>
    {{ media }}
{% endblock %}
👤dmand

Leave a comment