0

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?

  • Does this answer your question? [How to force Chrome browser to reload .css file while debugging in Visual Studio?](https://stackoverflow.com/questions/15562384/how-to-force-chrome-browser-to-reload-css-file-while-debugging-in-visual-studio) – Ivan Starostin Jan 23 '22 at 08:04

2 Answers2

0

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.

Marco
  • 2,371
  • 2
  • 12
  • 19
  • This problem occurs when I work locally, with the server that comes with django and is started by executing "manage.py runserver". In this case, how would it be resolved? – Sebastian Narvaez Jan 24 '22 at 13:50
  • I'm not aware of a caching function of the simple runserver command. Just disable ypur browser cache or force to reload the assets with Ctrl+F5 (Windows). – Marco Jan 24 '22 at 14:00
0

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)
Baks
  • 1
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 01 '23 at 09:26