【问题标题】:Django suddenly can't load static files anymoreDjango 突然不能再加载静态文件了
【发布时间】:2020-05-18 18:08:16
【问题描述】:

我有一个 django 项目,突然(更新 PyCharm 后)静态文件无法再加载。这是项目结构:

├── _quanttool
│   ├── _quanttool
│   │   ├── __init__.py
│   │   ├── asgi.py     
│   │   ├── settings.py
│   │   ├── urls.py
│   │   └── wsgi.py         
│   ├── _static
│   │   ├── css
│   │   ├── img
│   │   ├── js
│   │   ├── scss
│   │   └── vendor
│   ├── _templates
│   │   ├── base
│   │   ├── funds_tool
│   │   └── transaction_list
│   ├── funds_tool
.
.
.

│   ├── db.sqlite3
│   └── manage.py
├── venv
├── .gitignore
└── README.md

在我配置的settings.py文件中:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/_static/'
STATIC_ROOT = '_static'
STATICFILES_LOCATION = [os.path.join(BASE_DIR, '_static')]

在基本 HTML 模板中,我设置了 {% load static %}<link href="{% static 'css/sb-admin-2.min.css' %}" rel="stylesheet">

我真的不明白为什么我突然收到错误: "GET /_static/css/sb-admin-2.css HTTP/1.1" 404 1682" ...

知道为什么 Django 找不到静态文件了吗?

最好的

【问题讨论】:

  • 你有没有DEBUG=False
  • 不,它设置为 True,'django.contrib.staticfiles' 也包含在 INSTALLED_APPS 中。

标签: python django django-staticfiles


【解决方案1】:

注释掉 STATIC_ROOT = '_static' 并将以下代码添加到您的 settings.py 文件中。

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/_static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, '_static'),)

如果还是不行就在终端运行这个命令

$ python manage.py collectstatic

【讨论】:

  • 解决了这个问题。太感谢了。能否详细说明一下为什么 STATICFILES_LOCATION 突然停止工作,必须用 STATICFILES_DIRS 代替?
  • 这是设置的配置问题,我们需要根据内置的设置规则进行配置。默认是 STATICFILES_DIRS,而不是这个 STATICFILES_LOCATION。如果你是 Django 新手,那么我建议你关注 Django 的官方文档docs.djangoproject.com/en/3.0/ref/contrib/staticfiles/…djangoproject.com
猜你喜欢
  • 2020-12-10
  • 2020-05-03
  • 2017-11-08
  • 1970-01-01
  • 2022-08-17
  • 2012-04-30
  • 2013-12-09
  • 2021-11-20
  • 2021-05-30
相关资源
最近更新 更多