[Fixed]-Difficulty with Django and jQuery (why is $ undefined in the admin app?)

1đź‘Ť

âś…

You can use $(document).ready() as often as you want to on one page. It doesn’t redefine anything as you call it, but the call of ready() adds functions that are called when “the document is ready”.
To debug your code eg. use Firebug that will show you more detailled information about where the error occurs if there’s any!

30đź‘Ť

Adding this to the top of my .js file fixes it:

var $ = django.jQuery;

I’m not sure how to remove the jquery.init.js file, given that my project doesn’t contain any scripts that use $ for something other than jQuery.

👤Nick Heiner

8đź‘Ť

i solved this problem on this way, you have to include jquery.init.js (often its jquery.init.js from admin) in this file add following lines:

var django = {
    "jQuery": jQuery.noConflict(true)
};
var jQuery = django.jQuery;
var $=jQuery;

and u have in whole workspace jquery and $. For better code looking i prefer create my own jquery init file in project.

👤jinni

2đź‘Ť

Use the Firebug or Web Inspector JS console and type $ and/or jQuery. That’s the simplest way to find out if the library has been loaded correctly. In the unlikely case, that only jQuery is defined, you can wrap your script into it’s own scope:

(function($){
    // your code here…
})(jQuery);

If nothing is defined at the console, the problem is most likely with the file and I’d try AndiDog’s approach to see if there’s anything loaded at all.

👤polarblau

1đź‘Ť

In django one reason for this problem when you are using import_export plugin. In that case follow these steps –

  1. Create a folder under admin template directory named import_export (templates/admin/import_export)
  2. Create a file there named base.html (templates/admin/import_export/base.html)
  3. type the below code base.html file.

    {% extends “admin/import_export/base.html” %}
    {% load static %}
    {% block extrahead %}
    {{ block.super }}
    static/admin/js/vendor/jquery/jquery.js
    static/admin/js/jquery.init.js
    {% endblock %}

👤Nids Barthwal

0đź‘Ť

In Firefox, view the source code of the page, then click the link “/media/js/jquery.min.js” to see whether it loaded. Most probably you’re getting a 404 because you didn’t define the media URL correctly.

You can also use the development server for this purpose, it will show you all requests and the HTTP status code returned.

👤AndiDog

0đź‘Ť

I wrapped my js code to use jQuery:

window.onload = function () {
    if (django.jQuery('body').hasClass('change-list')) {
        ....
    }
}

-1đź‘Ť

You probably forgot to include {{ form.media }} in your template.

👤Teddy

Leave a comment