89๐
-
Clearing static file
python manage.py collectstatic --noinput --clear
. This will clear the statics beforehand. (Caution: Read before use.) -
Clear the browser cache
-
Add a random string after the JavaScript file include, e.g.
jquery.js?rand=23423423
, with each load.
31๐
It sounds like both your browsers have the javascript file cached. In Chrome you can clear the cache by pressing Ctrl
+ Shift
+ Del
and ticking just โCached images and filesโ. Firefox probably has a similar shortcut.
You can take a look at this question on tips to disable caching of static files on your development server altogether.
- [Django]-How do I perform HTML decoding/encoding using Python/Django?
- [Django]-Serving Media files during deployment in django 1.8
- [Django]-How can I find the union of two Django querysets?
25๐
You need to bust the browser cache. This template tag will output a time based uuid when DEBUG=True
. Otherwise it will look for a PROJECT_VERSION
environment variable. If that is not found it will output a static version number.
import os
import uuid
from django import template
from django.conf import settings
register = template.Library()
@register.simple_tag(name='cache_bust')
def cache_bust():
if settings.DEBUG:
version = uuid.uuid1()
else:
version = os.environ.get('PROJECT_VERSION')
if version is None:
version = '1'
return '__v__={version}'.format(version=version)
You would use in a template like this:
{% load cache_bust %}
<link rel="stylesheet" href="{% static "css/project.css" %}?{% cache_bust %}"/>
and here is the resulting output:
<link rel="stylesheet" href="/static/css/project.css?__v__=7d88de4e-7258-11e7-95a7-0242ac130005"/>
- [Django]-DateTimeField doesn't show in admin system
- [Django]-How to assign items inside a Model object with Django?
- [Django]-OneToOneField() vs ForeignKey() in Django
19๐
โChanges of staticfiles is not workingโ. There can be multiple reasons for that.
-
Your browser is
storing cache
of your static files.Solution (1): Open
Incognito/Private window
Solution (2): Use hard refresh:
- For mac:
cmd + shift + r
- For others:
ctr + shift + r
- For mac:
-
If youโre facing this issue in production then follow the steps below:
-
Remove
staticfiles
folder by following command:
sudo rm -rf staticfiles
[inside your project directory] -
Now run
collectstatic
command:python3 manage.py collectstatic
-
Restart
gunicorn
, by following command:sudo systemctl restart gunicorn
-
Restart
nginx
, by following command:sudo systemctl restart nginx
-
Sometimes browser stores thes staticfiles data (as caches) for a certain time. After couple of hours the problem may gone.
Hope this will fix you issue.
- [Django]-How can I temporarily disable a foreign key constraint in MySQL?
- [Django]-In Django, how do I check if a user is in a certain group?
- [Django]-Django-taggit โ how do I display the tags related to each record
13๐
Instead of using complicated solutions you can add extra parameter to your includes in the templates.
For static includes:
<script src="{% static 'js/polls/polls.js' %}?version=1"></script>
For direct includes:
<link rel="stylesheet" type="text/css" href="/site_media/css/style.css?version=1" />
Note the ?version=1
in the code. Every time youโre modifying the css/js file, change this version in the template, so browser will be forced to reload the file.
And if you want to avoid caching at all for some unknown reason, you may use the current timestamp instead of version:
<link rel="stylesheet" type="text/css" href="/site_media/css/style.css?{% now "U" %}" />
- [Django]-How to spread django unit tests over multiple files?
- [Django]-Select between two dates with Django
- [Django]-Django Rest Framework Conditional Field on Serializer
6๐
One solution is to change the settings to the following:
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'
What this does is create a copy of the static file with a content hash in the file name (when running collectstatic
). This way when the contents are changed the filename is changed and the old cache wonโt be used. The only problem with this is it doesnโt get used when in DEBUG = True
mode so you have to do a shift-reload to do a hard reload.
You can read the docs on ManifestStaticFilesStorage for more info.
EDIT: I found a solution for making sure static files are not cached in dev and posted it on another question.
- [Django]-In a Django form, how do I make a field readonly (or disabled) so that it cannot be edited?
- [Django]-How to find pg_config path
- [Django]-Django dynamic model fields
4๐
I have also struggled with this problem for hours. I have tried to inject random string using Javascript, but this method seems stupid and ugly-looking. One possible way to handle this problem is to introduce a custom tag. See this document for details:
Specifically, you need to create a package called templatetags
in whatever apps you have created (or create a new one if you want). And you create any file in this package, and write something like this:
from django import template
from django.utils.crypto import get_random_string
from django.templatetags import static
register = template.Library()
class StaticExtraNode(static.StaticNode):
def render(self, context):
return super().render(context) + '?v=' + get_random_string(32)
@register.tag('static_no_cache')
def do_static_extra(parser, token):
return StaticExtraNode.handle_token(parser, token)
def static_extra(path):
return StaticExtraNode.handle_simple(path)
then you can use tag {% static_no_cache '.../.../path...' %}
to create a path with random arguments!
I hope this would help!
- [Django]-Django urls without a trailing slash do not redirect
- [Django]-ValueError: The field admin.LogEntry.user was declared with a lazy reference
- [Django]-Redirect to Next after login in Django
4๐
For me after re collecting the static files Just Changes reflected for me.
$ python manage.py collectstatic --noinput --clear
Now run your server, hope it works.
$ python manage.py runserver
- [Django]-Django: How to manage development and production settings?
- [Django]-Remove pk field from django serialized objects
- [Django]-Folder Structure for Python Django-REST-framework and Angularjs
2๐
A simple way to get rid, do a hard refresh cmd+shift+r/ctr+shift+r
A hard refresh is a way of clearing the browserโs cache for a specific page, to force it to load the most recent version of a page.
on browser cmd+shift+r/ctr+shift+r
- [Django]-Django models: mutual references between two classes and impossibility to use forward declaration in python
- [Django]-Django 1.7 throws django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet
- [Django]-Tying in to Django Admin's Model History
2๐
first run python manage.py collectstatic --link -l
then python manage.py collectstatic
do not use python manage.py collectstatic --noinput --clear
it will bring down your server.
- [Django]-What is the difference render() and redirect() in Django?
- [Django]-Django โ limiting query results
- [Django]-AccessDenied when calling the CreateMultipartUpload operation in Django using django-storages and boto3
1๐
Simply running python manage.py collectstatic
should do the trick. Then hard refresh browser with ctrl + F5
which should work on all browsers.
- [Django]-How can I get all the request headers in Django?
- [Django]-Django queryset filter โ Q() | VS __in
- [Django]-Django-taggit โ how do I display the tags related to each record
- [Django]-How to stop gunicorn properly
- [Django]-Django: multiple models in one template using forms
- [Django]-How to get Request.User in Django-Rest-Framework serializer?
0๐
If nothing else works, search for the file name in the project and look for an unexpected copy. If you saved to the wrong location (different app) at some point, or splintered off a new app from an old, load priority may be playing tricks on you.
- [Django]-Django โ No such table: main.auth_user__old
- [Django]-Django template includes slow?
- [Django]-What is the benefit of using a HyperlinkedModelSerializer in DRF?
0๐
If you donโt want to refresh the browser cache each time you change your CSS and JavaScript files, or while styling images, you need to set STATIC_URL
dynamically with a varying path component. With the dynamically changing URL, whenever the code is updated, the visitorโs browser will force loading of all-new uncached static files. In this recipe, we will set a dynamic path for STATIC_URL
using time of last edit in os.
import os
from datetime import datetime
def get_file_changeset(absolute_path):
timestamp = max(map(lambda x: os.path.getmtime(x[0]), os.walk(os.path.join(absolute_path, 'static'))))
try:
timestamp = datetime.utcfromtimestamp(int(timestamp))
except ValueError:
return ""
changeset = timestamp.strftime('%Y%m%d%H%M%S')
return changeset
And next change in your SETTINGS
:
from utils.misc import get_file_changeset
STATIC_URL = "/static/%s/" % get_file_changeset(BASE_DIR)
How it works:
The get_file_changeset()
function takes the absolute_path
directory as a parameter and calls the os.path.getmtime()
to each file in each nested directory and finds the last-edited file (with its max edit time). The timestamp is parsed; converted to a string consisting of year, month, day, hour, minutes, and seconds; returned; and included in the definition of STATIC_URL
.
Note: With this you have to reload dev server each time when you edit your static files.
- [Django]-Best practice for Django project working directory structure
- [Django]-Can I access constants in settings.py from templates in Django?
- [Django]-How do I filter ForeignKey choices in a Django ModelForm?
0๐
I was chasing a css static file change tonight. Going thru a Django tutorial.
My Django html page would not show the updated css to my base.css file.
I would see the original base.css but no my update to file.This is on a dev environment.
I did not think django cached static on dev and only after running coll ecstatic in production.
For a quick work around I changed the name of my test sites. base.css file to base1.css and the html page link to base1.css
reloaded page and my updated css took affect. No best solution. but quick fix.
- [Django]-How to strip html/javascript from text input in django
- [Django]-How do I POST with jQuery/Ajax in Django?
- [Django]-Determine variable type within django template
0๐
For a window user, ctrl+f5 does the job on a development server and if this doesnโt work then using the command python manage.py collectstatic is working else other ways mentioned in some answers are really risky so itโs better to have a backup of your static files.
- [Django]-Django MEDIA_URL and MEDIA_ROOT
- [Django]-Ignoring Django Migrations in pyproject.toml file for Black formatter
- [Django]-How to completely uninstall a Django app?
0๐
Private Tab works for me. Thatโs why we should use private tabs at the time of development
- [Django]-Django: import auth user to the model
- [Django]-Django, Models & Forms: replace "This field is required" message
- [Django]-How do i pass GET parameters using django urlresolvers reverse
-1๐
Your browser will cache images and files (javascript included). First, clear just your cached images and files. Then use incognito mode in chrome or private browsing in firefox while you are making changes to your .js files so you see them instantly after a page refresh
- [Django]-Django removing object from ManyToMany relationship
- [Django]-Adding a user to a group in django
- [Django]-What is the best django model field to use to represent a US dollar amount?