I am using Whitenoise to serve static files (images, css, js) for a Django site. Now my problem is that the static files seem to be "cached to much"(?) when working locally. Description of actions:
- Initially my static files are served correctly
- I edit a file in
static/
- I run
./manage.py collectstatic
(which correctly identifies one updated file). - When going to
http://127.0.0.1:8000/
my browser consistently shows the old stale version of the file. I have even tried completely removing the generatedstaticfiles/
folder - and the browser still seems to be able to dig out an old version of the file?
This is when running locally in debug mode. Do not have a consistent understanding of how it is in production, but I think it works better (as it should?) there.
My configuration:
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
....
INSTALLED_APPS = [
# My apps
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
...
...
STATIC_URL = 'static/'
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
STATIC_ROOT = BASE_DIR / 'staticfiles'
STATICFILES_DIRS = [
("js" , BASE_DIR / "static/js"),
("css" , BASE_DIR / "static/css"),
("img" , BASE_DIR / "static/img")
]
I guess the problem is that I do not really understand the Whitenoise
model - slightly frustrating as this should be quite simple??
Update: I have tested this in Firefox with Ctrl-Shift R to reload the page, and got the old version. But when actually deleting the browser cache explicitly things work. feels a bit excessive that I have to manually wipe the browser history - but I can live with that.
CodePudding user response:
If a hard reload works, then the browser is most likely caching the parent request (rendered html result).
So if you have an endpoint, /myendpoint/
, that returns a rendered template, where the template contains the static file reference handled by whitenoise , css/mycss.{hash}.css
, the parent request is being cached and the browser doesn't see the updated static file reference.
Django has some tools that help dealing with caching.
https://docs.djangoproject.com/en/3.2/topics/cache/#controlling-cache-using-other-headers
If you want to make sure the client always get's the latest page you can use the never_cache
decorator.
from django.views.decorators.cache import never_cache
@never_cache
def myview(request):
...