[Django]-Problems with Django template cache refresh

3👍

Ken’s answer works for me.

If you are using django, in the template, just use something like

    <img src="/image.jpg?cachebuster={{uuid}}" /> 

and pass the uuid from server side.

I’d like to vote up Ken’s answer but unfortunately I don’t have enough reputation to do so. Sorry I have to answer this question again.

👤zephyr

2👍

Are you keeping the same image name but changing the image? I’m guessing it is the browser cache that is causing you problems and not the django cache.

Try adding a query string to the end of the image, it should help invalidate the browser cache. it doesn’t matter what you put in they query string, it just needs to be unique

<img src="/image.jpg?cachebuster=blah23" />

0👍

I was having a browser cache refresh problem, and Ken Cochrane’s answer led me to a solution.

My problem was with the model detail page. After updating the record, coming back to the detail page, the browser showed what was in the cashe —
the page without the updates. This sucked big time! Imagine a user’s confusion after saving some updates, only to misunderstand from the (browser cache version of) detail page that the updates were not saved! But they were saved, the problem was the browser was showing the cached version.

Ken Cochrane’s solution: adding a query string with something unique. That worked for me! At first, I just added timezone.now() formatted to be URL compatible, such as ?utc=2018-02-19_22.57.30 (in URLs, colons proceed the port, colons confuse the URL — cannot use colons).

The python format string: ‘%Y-%m-%d_%H.%M.%S’

This solved my problem, but this was forcing a refresh every time the user came back to the detail view page, even when there had been no update. Then it occurred to me: instead of using timezone.now(), use the model row’s last update timestamp. After an update, the last update timestamp will be later than the prior one, so the browser will refresh. If the user comes back again without any update, the the last update timestamp will be the same, so the browser can show the cached page.

So my query string is ?updated=2018-02-19_22.57.30

The solution could be used when keeping the same image name but changing the image file by using the file system timestamp of the image file for the query string. Only when the image changes, the timestamp will be different, and the browser will refresh. When the image file is the same, the timestamp will be the same, so the browser can show the cached version.

Leave a comment