Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django.jQuery $ is not a function message

in my django project i would to clean a field value based on an event in another field on a django admin add/edit form. i insert in the admin/change_form.html my call to js :

{{ block.super }}
    <script type="text/javascript" src="{% static 'js/admin.js' %}"></script>
    {{ media }}
{% endblock %}

then my admin.js:

(function($) {
    $(document).ready(function() {
        $("select[name='main_id']").change(function() {
            $("select['test_id']").val('');
        });
    });
})(django.jQuery);

but when i open my django-admin page in console i get:

Uncaught TypeError: $ is not a function

on the "$(document).ready(function() {" line.

Someone can help me with this error?

So many thanks in advance

like image 401
Manuel Santi Avatar asked Sep 24 '19 20:09

Manuel Santi


3 Answers

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.

like image 102
Daniel Morell Avatar answered Nov 05 '22 12:11

Daniel Morell


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
    )
like image 4
AleMal Avatar answered Nov 05 '22 11:11

AleMal


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 %}
like image 2
Kostandy Avatar answered Nov 05 '22 12:11

Kostandy