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

StackOverflow https://stackoverflow.com/questions/23458391

Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top