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