6

In my Django project the application my_app has a template which references a javascript static file:

<script src="{% static 'my_app/my_script.js' %}"></script>

Once I installed my_script.js in my_app/templates/my_app, everything seemed to work. At some point I overwrote my_script.js with a different script, such that my_script.js has a different content now.

However, when I load my_app with my browser, it loads the old my_script.js, although it does not exist anymore. How can I resolve it? Thanks.

jazzblue
  • 2,411
  • 4
  • 38
  • 63

3 Answers3

7

I often use ?v=00001 or any define number to force clear cache in browser. So in your case it could be:

<script src="{% static 'my_app/my_script.js?v=00001' %}"></script>

Or:

<script src="{% static 'my_app/my_script.js' %}?v=00001"></script>

Next time you change the script, increase the number to 00002. Of course there are many ways to do this but I still prefer this method.

Hieu Nguyen
  • 8,563
  • 2
  • 36
  • 43
2

You can add a cache-busting ?get=parameter. I like to define a {% statichash %} template tag that reads the file and appends a hash of the file contents as a get param. This is similar, uses the file's modified time instead of hash, but same idea:

https://bitbucket.org/ad3w/django-sstatic/src/4401a4bc3058618dfc2eafaee6a23d287a99ede5/sstatic/templatetags/sstatic.py?at=default

AdamKG
  • 13,678
  • 3
  • 38
  • 46
  • Thanks. Am I supposed to use"?get=parameter" like this: ? And then add {% statichash %} to the template? I have just tried that and it does not seem to like {% statichash %}. – jazzblue Jul 21 '13 at 23:28
  • no, sorry, ?get=parameter is just me trying to be clever and combine the explanation and an example. Just copy in the sstatic template tag code from the bitbucket link into your templatetags file (look up the django docs on how to add one if you don't have one already) and use {% sstatic 'foobar' %} instead of {% static 'foobar' %}. Hieu Nguyen's approach should also work, but haven't tested it, might need to move the ?v=0000X to after the %}. – AdamKG Jul 21 '13 at 23:36
  • Is there any way to do this without replacing the {% static %} of every file with {% statichash %}? – Anuvab Mohanty Nov 01 '18 at 06:09
0

I fixed it by including writing code to refresh the browser. This way, it will always get the latest updated static files instead of reading from its cache.

There's 3 way to do this.

  1. Manually refresh the page

Using Windows OS with browsers Google Chrome or IE9, hit (CTRL + F5)

  1. Refresh the page at certain time intervals (in this example, browser refreshes every 3 seconds) <head>

    <meta http-equiv="refresh" content="3" >

    </head>

  2. Refresh the page when a user clicks a button

    <form>

    <INPUT TYPE="button" onClick="history.go(0)" VALUE="Refresh">

    </form>

Chee Loong Soon
  • 3,601
  • 3
  • 17
  • 21