Django: How to get a static file path in a development environment?

First, consider some of the premises. I use the following "trick" to prevent unwanted cache cache of static files (CSS, JS, etc.):

<script src="{{ STATIC_URL }}js/utils.js?version=1302983029"></script> 

When the version line changes the next time the page loads, it forces the browser to retrieve the static file from the server again. (Google css caching) for articles about this trick.)

I want the browser to get the latest version of the static file, but I also want to enable browser caching when the file has not changed. In other words, I want the version line to change if and only if the static file has been updated. I would also like to automatically generate a version string.

For this, I use the last modified time of the static file as the version string. I am making a special template tag for this:

 <script src="{% versioned_static 'js/utils.js' %}"></script> 

And this is how the template tag works:

 import os.path from django import template from django.conf import settings class VersionedStaticNode(template.Node): ... def render(self, context): # With the example above, self.path_string is "js/utils.js" static_file_path = os.path.join(settings.STATIC_ROOT, self.path_string) return '%s?version=%s' % ( os.path.join(settings.STATIC_URL, self.path_string), int(os.path.getmtime(static_file_path)) ) 

To get a static file with the last modified time, I need to know its path to the file on the system. I get this file path by attaching settings.STATIC_ROOT and the relative file path from this static root. This is good and good for a production server, since all static files are collected in STATIC_ROOT .

However, on the development server (where the manage.py runningerver command is used), static files are not collected in STATIC_ROOT . So, how do I get the path to a static file when working in development?

(To clarify my purpose: the caching situation I want to avoid is a browser that uses a mismatch between the new HTML and the old CSS / JS. In production, this can be very confusing for users, in development it can confuse me and other developers, and makes us refresh pages frequently / clear browser cache.)

+4
source share
1 answer

If you are using django.contrib.staticfiles, here is an excerpt from the findstatic command (django / contrib / staticfiles / management / commands / findstatic.py) that should help. It uses finders.find to find the file.

  from django.contrib.staticfiles import finders result = finders.find(path, all=options['all']) path = smart_unicode(path) if result: if not isinstance(result, (list, tuple)): result = [result] output = u'\n '.join( (smart_unicode(os.path.realpath(path)) for path in result)) self.stdout.write( smart_str(u"Found '%s' here:\n %s\n" % (path, output))) 
+13
source

Source: https://habr.com/ru/post/1397742/


All Articles