Throughout the django documentation and a lot of tutorials people seem to pick freely between using the {% static %}
tag, and using {{ STATIC_URL }}
with the correct context processor.
Can someone explain what the difference between them is, and any advantages there might be to using on over the other.
{% load static %} tells django to load a set of template tags/filters defined in the file static.py (in a folder templatetags in any of the apps of your project). The same way you can define your own tags, put them in a file util_tags.py and load them with {% load util_tags %} . – dirkgroten.
The {% static %} template tag generates the absolute URL of static files. That's all you need to do for development. Reload http://localhost:8000/polls/ and you should see that the question links are green (Django style!) which means that your stylesheet was properly loaded.
STATIC_URL is simply the prefix or url that is prepended to your static files and is used by the static method in Django templates mostly. For more info, read this. STATIC_ROOT is the directory or location where your static files are deployed when you run collectstatic .
Static loading is any load that is applied slowly to an assembly, object or structure. Static loads are also those that remain consistent and do not move at all. They are used to work out the maximum load for a range of structures and objects as well as for determining the ultimate tensile strength of materials.
The {% static %}
template tag is aware of your STATICFILES_STORAGE
, using the STATIC_URL
setting is not.
Use the template tag.
Manually concatenating is bad practice ("do I need a slash?"), and will eventually bite you, generally when you decide to change static files storage.
Here's an example. You might want to use AWS S3 for static files hosting, all the while not making your files public. You'll then be serving those using AWS S3 authenticated URLS.
The correct URL will look something like:
https://s3.amazonaws.com/bucket/file.ext?signature=1234
The {% static %}
template tag will let you add the signature. Using STATIC_URL
will not.
In a similar fashion, if your static files storage fingerprints your files, using STATIC_URL
will not work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With