Why is {% load static %} a dependency for {% get_media_prefix %}? - django

I've been using {% get_media_prefix %} for a very long time. I was explaining this to someone when he pointed this out.
Why do I need to declare {% load static %} in order to use it?
It even uses in the documentation's example code here.
To an extent I understand that static files and media files are similar in nature. Even when we use them with combination of nginx+gunicorn, nginx handles both of them(we let everything else proxy, but not these).
But still we have a separate MEDIA_URL and STATIC_URL as well as MEDIA_ROOT and STATIC_ROOT defined for these files.
Then why {% load static %} needs to be declared in order to use {% get_media_prefix %} ?
Thanks in advance.

In order to use a template tag in your HTML you must first load the module that contains it.
So, accorrding to the source code of get_media_prefix template tag, this template tag lives inside django/templatetags/static.py.
That's why you have to load it every time you use it, in every HTML template.
This, of course, applies to every template tag usage. At the top of every HTML file you load the template tags and then you use them. Just like you import a function in your python code.
UPDATE: From the Django 1.3 release notes:
In previous versions of Django, it was common to place static assets in MEDIA_ROOT along with user-uploaded files, and serve them both at MEDIA_URL. Part of the purpose of introducing the staticfiles app is to make it easier to keep static files separate from user-uploaded files. Static assets should now go in static/ subdirectories of your apps or in other static assets directories listed in STATICFILES_DIRS, and will be served at STATIC_URL.
As you can see, Django used to treat both static and media the same. Since Django 1.3 this changed, but the template tag not. No big deal. It's just a convention.

Related

Do I really need to use {% load static %} in Django Templates?

I am using Django 3, the latest version. I have defined the static files directories properly as required.
Currently to display an image, both the following source codes work fine.
Code 1:
<img src="static/img/logo.png">
Code 2:
{% load static %}
<img src="{% static 'img/logo.png' %}">
Since both the code snippets are working and running fine without any problems, I am wondering why not to simply use the way of Code 1 above and refrain from the extra lines of Code 2.
Which one would be beneficial and why? Please guide.
The base/master level templates would work without static tag and maybe considered for performance.
However for other level templates either nested or in app templates or nested urls, it's required to be reference with static as it would minimise chances of error. So for all other templates it is recommended to use static tag.

{% load static %} and {% load staticfiles %}: which is preferred?

I'm not sure what the difference is, it seems like both of them are working. I googled around, and seems like they are pretty much same thing.
Just out of curiosity, which one do people use in the field?
I read that but still don't know when to use which, and which one people in the field use. Mine works for both of them. At first I thought it's loading static folder but it works for staticfiles too... –
For the moment (Django 1.9 and earlier), {% load staticfiles %} loads the static templatetag from the contrib app that has more features than the built-in django.core.static.
The most important difference is staticfiles can manage files stored on CDN, since its resolver can manage hashes for example. core.static only append STATIC_URL to the static filename, which is not enough if you're processing your files (e.g. adding md5 hash to clear cache between releases)
This difference is due to the fact that managing non-local storage files was not dedicated to be included in the core package of Django, but was still useful to many developers to be implemented as a official contrib package. So if you started to use staticfiles, you had to remember to use it every in your templates. BUT, some problems could appear, for example when using Media classes so the decision has been to merge those two templatetags into one and use a different behaviour whether the developer has django.contrib.staticfiles in its INSTALLED_APPS or not.
From Django 1.10 and onwards (also see ticket in Django tracker), the {% load static %} is going to use staticfiles internally if activated (oherwise keep default behaviour), and the templatetag in the contrib package will be deprecated to avoid confusion.
TL;DR
Before Django 1.10: staticfiles loads a templatetags that can manage non-local storage where static can't (or not easily) ;
From Django 1.10: contrib.staticfiles app still exist but its templatetags will be removed only the {% static %} templatetags remains ;
From Django 2.0 (I believe): {% load staticfiles %} is removed.
For now, use staticfiles templatetags if you use the related contrib app (and you know why you are using it) until Django 1.10, otherwise just use static.
just an interesting piece of code inside the 'django/contrib/staticfiles/templatetags/staticfiles.py' about this topic:
import warnings
from django import template
from django.templatetags.static import (
do_static as _do_static, static as _static,
)
from django.utils.deprecation import RemovedInDjango30Warning
register = template.Library()
def static(path):
warnings.warn(
'django.contrib.staticfiles.templatetags.static() is deprecated in '
'favor of django.templatetags.static.static().',
RemovedInDjango30Warning,
stacklevel=2,
)
return _static(path)
#register.tag('static')
def do_static(parser, token):
warnings.warn(
'{% load staticfiles %} is deprecated in favor of {% load static %}.',
RemovedInDjango30Warning,
)
return _do_static(parser, token)
so ill dare to assume {% load staticfiles %} is going to be removed after the django 3 release :)

{% load staticfiles %} - Does it pre-load all recursively or on demand?

In django I'm curious concerning the {% load staticfiles %} template directive.
In static files I have a sass directory, and sass in turn can have a cache which gets quite large. I'm not inquiring of 'best practice' though, but in any case are all files pre-loaded or not?
If I'm only using, for instance, fonts, bootstrap, a personal stylesheet, etc...is it going to load all the things I'm not using?
Very curious about this. I don't want to use up more resources than needed.
You've completely misunderstood what the load tag does. All it does is make a template tag library available for the template to use: in this case, the "staticfiles" library which includes the definition of the {% static %} tag. Without that load statement, you can't use that tag.
It doesn't do anything with the staticfiles itself - indeed it can't, loading them is a matter for the browser, which will do whatever is in your HTML.

Parsing static stylesheets into template

I have 6 stylesheets which i am generating with LESS. Since i want to automate this procedure i would like to know if there is any way to parse the stylesheets directly into my template? I need a hybrid between the include and static tag. Static only gives a path, while i want the include functionality being able to parse it.
Is it possible to combine them include and static somehow:
{% include {% static 'test/test.js' %} %}
Update: Its very important i mention that the test.js also contains {% static %} tags.
If it needs to be parsed as a template, it's not a static file and shouldn't be stored in the static directory. That's for assets that need to be served directly from your webserver.
Put it in your templates folder - in a "scripts" subdirectory if you like - and use the standard include tag.

Difference between "load static from staticfiles" and "django.core.context_processors.static" in Django

As I am learning about how Django handles static files, I have seen two different ways of serving static files while still allowing portability.
One way is to do the following in the template:
{% load static from staticfiles %}
<img src="{% static "images/hi.jpg" %}" alt="Hi!" />
as documented here on the Django docs.
The other way I see is to load the context processor for static files, and then use
<img src="{{ STATIC_URL }}images/hi.jpg" alt="Hi!" />
as noted here on the Django docs. When using this method, I change STATIC_URL based on
if DEBUG:
STATIC_URL = 'localhost'
else:
STATIC_URL = 'some_static_server_url'
Which is considered better practice? Is one way better than the other? For example, this SO question has both methods as answers, and this one has the second method. Any insights would be helpful.
Both methods are essentially the same when using Django's default StaticFilesStorage. Both methods are ignorant of any actual files. Both methods just join together the STATIC_URL setting and the actual file path.
There can be a difference when using a custom file storage backend. If you need flexibility, e.g. if some files are stored with different static urls, you can override the backend's url method to return an url based on the actual location of the file. That won't be possible using the STATIC_URL setting. However, this situation is quite rare: most servers store their static files in a single location either on the same server or with a third-party service.
When you define the STATIC_URL setting and the static files are on the same domain as the website, it's better to define it as a root-relative url, e.g. '/static/'. This increases portability and is less likely to cause errors. You will no longer have to worry if you have covered all systems where the code can be deployed.