How to use jQuery with Django?

16,698

Solution 1

Usually jquery, js, css, images and most of other static contents are handled as static files and not as django templates. Read managing static files docs.

Solution 2

For jQuery, you can use Google API :

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

And for Django, Did you configure a path for your scripts/médias etc... ? (in settings.py maybe ?)

Solution 3

To add to what others have written, if you want to make JQuery available throughout your site/app and you don't like external dependencies such as Google you can do the following:

  1. Download the latest "compressed, production" JQuery at https://jquery.com/download/ - for example, on the command line in your static directory (might be <projectname>/static): wget https://code.jquery.com/jquery-2.1.3.min.js
  2. Add a reference to load JQuery in your site's "base" template file (might be <projectname>/<appname>/templates/base.html) - for example: Add <script src="{% static 'jquery-2.1.3.min.js' %}"></script> in the <head> section
  3. Test the JQuery installation by adding something like the following to one of your templates:

    <script type="text/javascript"> $(document).ready( function(){ $("#jqtest").html("JQuery installed successfully!"); } ); </script> <p id="jqtest"></p>

  4. If necessary/usual after making template updates, restart your Django server, then load a page which uses the template with the test code

Share:
16,698
user1530318
Author by

user1530318

Updated on June 11, 2022

Comments

  • user1530318
    user1530318 almost 2 years

    I am interested in using the jQuery tablesorter but somehow am unable to. I have followed the instructions and have placed jquery.js and the tablesorter.js in the same folder as my templates (the folder where the html file is). Unfortunately, when trying to access the .js files, it keeps hitting a 404, which I'm assuming means that the files are not on the correct path. Any ideas for this fix?

    Does django have a special place to place these js files? (not in the templates folder?)

    <script type="text/javascript" src="jquery-latest.js"></script> 
    <script type="text/javascript" src="jquery.tablesorter.js"></script>
    <script type ="text/javascript">
        $(document).ready(function() 
        { 
           $("#myTable").tablesorter(); 
        } 
    ); 
    

    The myTable is the same exact table as the one in the examples