Django won't refresh staticfiles

前端 未结 15 1156
渐次进展
渐次进展 2020-12-07 18:31

This is annoying. I have a javascript file referenced on a django template:

 
15条回答
  •  南笙
    南笙 (楼主)
    2020-12-07 19:05

    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_URLdynamically 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.

提交回复
热议问题