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?

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.