Django:找不到静态文件

Django : cannot find the static files

在我的Django项目中,设置如下: 一个设置文件夹,包括一个 base.py 和一个 production.py 文件。 基础文件夹定义了一个考虑到这棵树的路径:

BASE_DIR = os.path.dirname(
    os.path.dirname(os.path.abspath(
    os.path.join(__file__, os.pardir))))

静态定义如下:

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

当我启动 collectstatic 时,静态文件夹按计划安装在项目的根目录下。 但是,html 页面都找不到静态文件,尽管配置为 seach:

{% load static %}

<!DOCTYPE html>
<html lang="eng">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, initial-scale=1">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
    <link rel="stylesheet" href="{% static 'style_sheet.css' %}">
    <title>{% block title %}Advocacy Project{% endblock %}</title>

</head>

当我检查 findstatic 时,它似乎没有查看正确的文件夹:

python manage.py findstatic style_sheet.css --settings my_project.settings.production --verbosity 2
No matching file found for 'style_sheet.css'.

Looking in the following locations:
  /Users/my_name/Documents/my_project/venv/lib/python3.7/site-packages/django/contrib/admin/static 

我的问题是:如何让 Django 签入正确的文件夹?

首先检查您的设置中 debug = False 或 True。 Django 不会在 Debug = False 模式下托管您的静态文件。您必须使用 whitenoise 之类的东西来托管生产中的静态文件。

感谢 ASFAW AYALKIBET 的支持,这里是使用多种设置在 Django 上安装 Whitenoise 的详细过程。

  1. 安装 Whitenoise pip install Whitenoise
  2. 在项目文件夹中创建 settings 文件夹。
  3. 在此文件夹中添加 base.pyproduction.py 以及 __init__.py 文件。
  4. production.py中添加
DEBUG = False
  1. 在设置中,修改BASE_DIR如下: BASE_DIR = Path(__file__).resolve().parent.parent.parent insert 'whitenoise.runserver_nostatic'in INSTALLED_APPS and 'whitenoise.middleware.WhiteNoiseMiddleware' in MIDDLEWARE,(cf whitenoise official doc).
  2. 再次在设置中,添加STATIC_ROOT = BASE_DIR / 'staticfiles'
  3. 在wsgi.py修改设置路径: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_project.settings.production')
  4. 然后您可以使用以下方法收集静态文件: python manage.py collectstatic --settings settings.my_project.production
  5. 启动服务器: gunicorn my_project.wsgi查看生产模式 python manage.py runserver --settings settings.my_project.base 使用调试模式。