Django,强制重新加载 css/js,以及collectstatic

问题描述 投票:0回答:3

假设我已经对我的开发计算机上的 css 文件进行了大量更新(我的浏览器设置为忽略缓存,并不总是立即看到更新)。

这个问题和其他地方,我看到了在链接中添加版本号的方法:

<link type="text/css" href={% static "/path/mystyles.css?version=2" %} rel="stylesheet">
,

这很好,但在开发机器上,我在控制台中收到错误,并且找不到文件:

GET http://127.0.0.1:8000/path/mystyles.css%3Fversion%3D2 net::ERR_ABORTED 404 (Not Found)

我读过,也许

collectstatic
会在开发端修复它,但有一个不祥的警告:

You have requested to collect static files at the destination
location as specified in your settings:

    /patttthhhhh/static

This will overwrite existing files!
Are you sure you want to do this?

当我跑步

collectstatic
时会发生什么?它将从哪里获取文件来覆盖这些文件?

css django static-files
3个回答
1
投票

最终轻松完成的是更改版本标签的格式:

<link type="text/css" href="{% static '/path/mystyle.css' %}?version=2" rel="stylesheet">

而不是:

<link type="text/css" href={% static "/path/mystyles.css?version=2" %} rel="stylesheet">

在开发和生产中都很好。


0
投票

推荐的方法是使用 django-compressor (usage) 之类的东西将 CSS 处理成单个文件,然后将哈希值烘焙到文件名或目录中。这样你的资产就会变成

/mystyles.beb23fe.css


0
投票

我发现做到这一点的最简单方法是:

在一个名为 context_processors.py 的文件中(我将其放入我的核心应用程序中):

import time


def version(request):
    return {"VERSION": str(time.time())}

然后在settings.py中进行配置:

TEMPLATES = [
    {
        ...
        "OPTIONS": {
            "context_processors": [
                ...
                "core.context_processors.version",
            ],
        },
    },
]

然后在我的模板中我有这个:

<link rel="stylesheet" href="{% static 'css/styles.css' %}?version={{VERSION}}">

它在生产中看起来效果非常好。

© www.soinside.com 2019 - 2024. All rights reserved.