简体   繁体   中英

django file not found error: when javascript file inside static directory trying to access another file in the static directory?

I am doing one django project. And I am able to access the "custom.js" file from static folder path.This is a line inside my "index.html" file.

<script type="text/javascript" src="{% static 'crypto_app/js/custom.js' %}" ></script>

But inside "custom.js" file it is using this :

$(window).ready(function() {
'use strict';
$.vegas('slideshow', {
  backgrounds:[
    { src: 'images/bg-slider/bg-1.jpg', fade:1000 },
    { src:'images/bg-slider/bg-2.jpg', fade:1000 },
    { src:'images/bg-slider/bg-3.jpg', fade:1000 }
})();

And hence, due to wrong file address, I am not able to access the images. And it is showing file not found.

Is there some django way to declare path of images as variable and accessing it from the "custom.js" file? Given below is my directory structure :

|   admin.py
|   apps.py
|   models.py
|   tests.py 
|   tree.txt
|   urls.py
|   views.py
|   
+---migrations
|   |   __init__.py|           
+---static
|   \---crypto_app      
|       +---css
|       |           
|       +---fonts      
|       +---images  
|       |   \---bg-slider
|       |           bg-1.jpg
|       |           bg-2.jpg
|       |           bg-3.jpg
|       |           
|       \---js
|               custom.js               
+---templates
|   \---crypto_app
|           index.html

First to answer your question, no there is no Django specific thing that makes you get paths for these images OOTB in your JavaScript file. Django would force you to access via HTML (as shown in example #2).

There's most likely some Django app that you can install.

Now on to solving your conundrum. Since you're using the {% static %} template tag to load your JavaScript you would need to do something similar.

Of course there's a few ways to make this happen:

1) Hardcode the URL, {% static %} basically concats your STATIC_URL together with the path you've supplied. So take the same URL and append it to the image urls. Assuming STATIC_URL is set to /static/ your new hardcoded urls would be something along the lines of /static/images/bg-slider/bg-1.jpg and so on.

2) Create an options object and tack it onto window . In your index.html :

<script>
    window.options = {
        staticUrl: {{ STATIC_URL }},
    };
</script>

Then use this in your JS code

backgrounds:[
    { src: `${window.options.staticUrl}images/bg-slider/bg-1.jpg`, fade:1000 },
}

Naturally if you have just the one place you do this, hardcoding would be the easiest option for you at this point in time. :)

Happy hacking!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM