【问题标题】:Django Website does not load static filesDjango网站不加载静态文件
【发布时间】:2022-12-09 00:28:50
【问题描述】:

我正在创建一个 django 项目,我在项目目录中有模板和静态文件夹。我可以呈现和查看 html 文件,但它无法加载存储在静态文件夹中的 css 文件。我已将加载静态标记放在我的 html 文件中,但是当我运行 python manage.py runserver 时,出现此错误

Performing system checks...

Watching for file changes with StatReloader
System check identified some issues:

WARNINGS:
?: (staticfiles.W004) The directory '/static' in the STATICFILES_DIRS setting does not exist.

System check identified 1 issue (0 silenced).
December 08, 2022 - 14:54:53
Django version 4.1.3, using settings 'brighterstrat.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

这就是我在 html 文件中引用静态文件的方式

<link rel="stylesheet" href="{% static 'css/bootstrap.min.css'%}">
<link rel="stylesheet" href="{% static 'css/style.css'%}">

设置.py

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = [os.path.join(BASE_DIR, '/static')]
STATICFILES_STORAGE = "django.contrib.staticfiles.storage.StaticFilesStorage"

我怎样才能让它加载css文件

【问题讨论】:

    标签: django django-templates django-staticfiles


    【解决方案1】:

    Django statics 可能会令人困惑,主要是因为两者之间的行为不同产品发展(即DEBUG=True

    回顾一下设置:

    # Url at which static files are served
    # It's the url the browser will fetch to get the static files
    # It's prepend to static name by the {% static %} templatetag
    STATIC_URL = "static/"
    
    # Directory where static files can be found
    # When DEBUG = True, static files will be directly served from there by 
    # the manage.py runserver command
    STATICFILES_DIRS = [BASE_DIR / "static"]
    
    # Directory to export staticfiles for production
    # All files from all STATICFILES_DIRS will be copied by 
    # manage.py collectstatic to this directory.
    # /! It will not be served by django, you have to setup 
    # your webserver (or use a third party module) 
    # to serve assets from there.
    STATIC_ROOT = BASE_DIR / "assets"
    

    在您的示例中,您似乎没有将文件放在 STATICFILES_DIRS 列出的目录中,因此请确保您拥有这些文件:

    | manage.py (root of your django app)
    | static
    |   |- css
    |   |   |- bootstrap.min.css
    |   |   |- style.css
    

    【讨论】:

      【解决方案2】:

      要调试它,您可以在设置中添加打印:

      print([os.path.join(BASE_DIR, '/static')])
      

      要解决此问题,您只需删除斜杠即可使其正常工作。

      来自os.path.join() docs

      如果组件是绝对路径,则所有先前的组件都将被丢弃,并从绝对路径组件继续连接。

      这就是 BASE_DIR 被切断的原因。

      【讨论】:

        猜你喜欢
        • 2017-11-08
        • 1970-01-01
        • 2012-04-30
        • 2020-12-10
        • 2013-12-09
        • 2021-11-20
        • 2021-05-30
        • 2017-11-08
        • 1970-01-01
        相关资源
        最近更新 更多