57👍
Since you are using django’s template language you can ONLY do this within your template between <script>
tags. In other words if you wished to use your pic2.src
javascript variable in an external script then you would need to declare it between <script>
tags like so
<script>
var pic2.src = "{% static "photos/1.jpg" %}"
</script>
And then you could access it in your external scripts that you might load like this:
<script type="text/javascript" src="{% static "js/my_external_script.js" %}"></script>
Regarding your question concerning load static
and load staticfiles
there is little distinction. Both act as a joiner for the STATIC_URL
in your settings.py
and the actual path to the file itself so both should work for your case. See here and here for more info.
20👍
If you need many static (or media) url’s in your .js
files, this might be more convenient:
<script>
var static_url = "{% get_static_prefix %}";
var media_url = "{% get_media_prefix %}";
</script>
Then both url’s are freely available in all javascript files.
- [Django]-Prepopulate Django (non-Model) Form
- [Django]-Cannot access django app through ip address while accessing it through localhost
- [Django]-Pipfile.lock out of date
13👍
You can assign the path in your template and then use it in your javascript file.
Template:
<script>
var url = "{% static 'photos/1.jpg' %}";
</script>
Javascript:
pic2.src = url
- [Django]-Determine complete Django url configuration
- [Django]-Django 1.3.1 compilemessages. Error: sh: msgfmt: command not found
- [Django]-How do I go straight to template, in Django's urls.py?
5👍
Easy Workaround! 🙂
index.html
<input type="hidden" id="pic-src" value="{% static 'photos/1.jpg' %}">
script.js
var pic2.src = $('pic-src').val();
- [Django]-What's the best way to start learning django?
- [Django]-Django: save() vs update() to update the database?
- [Django]-Django – How to rename a model field using South?