Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the difference between using {{STATIC_URL}} and {% static %}

Tags:

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.

like image 689
thomas Avatar asked Aug 23 '13 10:08

thomas


People also ask

What is {% static %} means in Python?

{% 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.

What is {% load static %} in Django?

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.

What does STATIC_URL do in Django?

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 .

What does load static mean?

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.


1 Answers

Abstract

The {% static %} template tag is aware of your STATICFILES_STORAGE, using the STATIC_URL setting is not.

Rule of thumb

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.

Examples

Authenticated URLs

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.

Fingerprinted URLs

In a similar fashion, if your static files storage fingerprints your files, using STATIC_URL will not work.

like image 53
Thomas Orozco Avatar answered Sep 22 '22 00:09

Thomas Orozco