Currently I have developed applications with django for a few months, I have noticed that once you finish developing the application interfaces and want to integrate them into the backend everything works correctly, time later it becomes a mess having to modify the static files, since django caches these files perhaps to render the templates more efficiently, however when I want to make changes I have to rename the file and reinsert it in my index.html so that django detects it "as a new file". As you can see, it is very annoying to work like this. Does anyone have an idea how to fix this problem?
2 Answers
The solutions depend on the web server technologies used. If you are using nginx as a web server for instance, you can kill the cache for some specific files like:
location ~* \.(css|js)$ {
expires -1;
}
But I do not recommend doing it that way. This will disable caching completely and force the clients to always download the assets even they have not changed. This is not good practice.
For this reason, I recommend the following approach: simply add a GET parameter after the assets you want to force to download:
<link href="style.css?v=1" rel="stylesheet" type="text/css">
That way, you can control whenever you want the frontend should load the assets again (change the parameter value), and you can still profit from caching your static assets.
This approach applies not only to Django but to all websites.
2 Comments
You can monkey patch view responsible for serving static files:
from functools import wraps
import django.views.static
def no_cache_static(f):
@wraps(f)
def static(*a, **kw):
response = f(*a, **kw)
response.headers["Cache-Control"] = "no-cache"
return response
return static
django.views.static.serve = no_cache_static(django.views.static.serve)