【问题标题】:Why won't Django load my static CSS files?为什么 Django 不加载我的静态 CSS 文件?
【发布时间】:2016-12-05 11:54:45
【问题描述】:

我无法让 Django 为我的 html 模板加载我的 CSS。我知道有很多这样的帖子,例如herehere,但我不确定这里还能做什么,因为我尝试了其中几种类型的解决方案都无济于事.

使用python manage.py runserver 加载我的网站会返回此日志:

[31/Jul/2016 01:58:29] "GET / HTTP/1.1" 200 1703
[31/Jul/2016 01:58:29] "GET /static/css/about.css HTTP/1.1" 404 1766

我不确定日志第二行末尾的 404 是否指 404 错误。

我尝试将静态文件添加到我的urls.py

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', TemplateView.as_view(template_name='about.html'))
]

urlpatterns += staticfiles_urlpatterns()

我已经尝试修改我的settings.py:

STATIC_ROOT = ''

STATIC_URL = '/static/'

STATICFILES_DIR = os.path.dirname(os.path.abspath(__file__)) + "/static/"

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder'
)

我当然在实际模板本身中使用了正确的加载方法:

{% load staticfiles %}
...
<link rel="stylesheet" href="{% static 'css/about.css' %}">

这是我的文件结构:

Personal_Website
|Personal_Website
||settings.py
||urls.py
||etc...
|static
||css
|||about.css

坦率地说,我不确定在这里还能做什么。我觉得我已经尝试了所有设置,但仍然得到相同的日志。

【问题讨论】:

    标签: python html css django


    【解决方案1】:

    你应该有这个在项目目录中提供静态文件...

    STATICFILES_DIRS = [os.path.join(BASE_DIR, "static"),]
    

    os.path.dirname(os.path.abspath(__file__)) 这是指向 Personal_Website 文件夹,其中设置所有文件都在那里...

    【讨论】:

    • 不幸的是,我得到了相同的结果。如果您需要更多信息,我的基本路径是 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    • @hasherr 这肯定会奏效。我在我的本地复制了完全相同的东西,并且正在工作......你能打印STATICFILES_DIRS它指向的地方......
    • 我似乎找不到打印出变量的好方法。有什么建议吗?
    • 在 settings.py 你可以print STATICFILES_DIRS 然后在控制台看到..
    • C:\\Users\\eklei\\Google Drive\\Development\\Personal_Website\\static
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    • 2021-07-22
    • 2017-10-08
    • 2019-12-30
    • 2020-08-31
    • 2017-12-09
    • 2018-02-03
    相关资源
    最近更新 更多