首页 > 解决方案 > Django:如何在共享模板中添加静态文件?

问题描述

我有不属于任何特定应用程序的共享模板。这是我的项目树:

.
├── root_app
│   ├── asgi.py
│   ├── forms.py
│   ├── __init__.py
│   ├── __pycache__
│   ├── settings.py
│   ├── urls.py
│   ├── views.py
│   └── wsgi.py
├── db.sqlite3
├── another_app
│   ├── admin.py
│   ├── api_services.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   ├── models.py
│   ├── __pycache__
│   ├── templates
│   ├── tests.py
│   ├── urls.py
│   ├── utils.py
│   └── views.py
├── manage.py
├── Pipfile
├── Pipfile.lock
├── README.md
├── requirements.txt
├── static
│   └── css
│       └── styles.css 
└── templates
    ├── base.html
    └── home.html

在我的设置文件中,我有:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

INSTALLED_APPS = [
    ...
    ...
    'django.contrib.staticfiles',
]
STATIC_URL = '/static/'

STATIC_DIR = [os.path.join(BASE_DIR, 'static')]

在我的 base.html 模板中,我试图以这种方式从 static/css/styles.css 调用 styles.css:

{% load static %}
<link rel="stylesheet" type="text/css" href="{% static "css/styles.css" %}" />

但服务器响应未找到:

"GET /static/css/styles.css HTTP/1.1" 404

我做错了什么?

标签: pythondjangodjango-staticfiles

解决方案


好像您正在开发中,所以 DEBUG 是 True。

STATICFILES_DIRS是 Django 将在其中搜索除每个已安装应用程序的静态文件夹之外的其他静态文件的文件夹列表。

尝试将此列表插入到您的设置中:

STATICFILES_DIRS = ['/home/path/to/your/static/',]

推荐阅读