Django - 全局静态文件

添加全局 CSS 文件

我们已经学习了如何在应用程序的 static 文件夹中添加静态文件,以及如何在应用程序中使用它。

但是,如果项目中的其他应用程序也想使用该文件呢?

那么我们需要在根目录下创建一个文件夹,并将文件放在那里。

仅仅在根目录下创建一个 static 文件夹是不够的,Django 会自动处理剩下的事情。我们需要告诉 Django 这些静态文件在哪里查找。

首先在项目根目录下创建一个文件夹,这个文件夹可以随意命名,在本教程中我将其命名为 mystaticfiles:

my_tennis_club
    db.sqlite3
    manage.py
    my_tennis_club/
    members/
    mystaticfiles/

在 mystaticfiles 文件夹中添加一个 CSS 文件,文件名可以随意命名,本例中我们将其命名为 myglobal.css:

my_tennis_club
    db.sqlite3
    manage.py
    my_tennis_club/
    members/
    mystaticfiles/
        myglobal.css

打开 CSS 文件并插入以下内容:

my_tennis_club/mystaticfiles/myglobal.css:

body {
  color: violet;
}

修改设置

您需要告诉 Django 在根目录下的 mystaticfiles 文件夹中查找静态文件,这需要在 settings.py 文件中完成:

添加 STATICFILES_DIRS 列表:

my_tennis_club/my_tennis_club/settings.py:

.
.

STATIC_ROOT = BASE_DIR / 'productionfiles'

STATIC_URL = 'static/'

#Add this in your settings.py file:
STATICFILES_DIRS = [
    BASE_DIR / 'mystaticfiles'
]
.
.

在STATICFILES_DIRS列表中,您可以列出Django应该查找静态文件的所有目录。

BASE_DIR关键字代表项目的根目录,与/"mystaticfiles"一起使用,指的是根目录下的mystaticfiles文件夹。

搜索顺序

如果存在同名文件,Django 将使用第一个匹配的文件。

搜索首先在 STATICFILES_DIRS 中列出的目录中进行,并按照您提供的顺序进行。然后,如果找不到该文件,则继续在每个应用程序的 static 文件夹中进行搜索。


修改模板

现在您拥有一个适用于整个项目的全局 CSS 文件,所有应用程序都可以访问它。

要在模板中使用它,请使用与 myfirst.css 文件相同的语法:

模板以以下内容开头:

{% load static %}

并像这样引用该文件:

<link rel="stylesheet" href="{% static 'myglobal.css' %}">

示例

my_tennis_club/members/templates/template.html:

{% load static %}
<!DOCTYPE html>
<html>
<link rel="stylesheet" href="{% static 'myglobal.css' %}">
<body>

{% for x in fruits %}
  <h1>{{ x }}</h1>
{% endfor %}

</body>
</html>
运行示例 »

没成功?

没错。您需要再次收集静态文件。


收集静态文件

运行 collectstatic 命令收集新的静态文件:

python manage.py collectstatic

这将产生以下结果:

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

    C:\Users\Your Name\myworld\my_tennis_club\productionfiles

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

Type 'yes' to continue, or 'no' to cancel:

请键入"yes":

Type 'yes' to continue, or 'no' to cancel: yes

这将产生以下结果:

1 static file copied to 'C:\Users\Your Name\myworld\my_tennis_club\productionfiles', 128 unmodified.

示例应该可以正常运行

启动服务器,示例即可运行:

python manage.py runserver

请在您的浏览器中查看结果:127.0.0.1:8000/testing/。

示例

my_tennis_club/members/templates/template.html:

{% load static %}
<!DOCTYPE html>
<html>
<link rel="stylesheet" href="{% static 'myglobal.css' %}">
<body>

{% for x in fruits %}
  <h1>{{ x }}</h1>
{% endfor %}

</body>
</html>
运行示例 »