首页 > 解决方案 > 无法在 Django 1.9 中加载 style.css

问题描述

我正在尝试在我的页面上加载 style.css。
我已经添加了STATICFILES_DIRS如下路径,

STATIC_URL = '/static/'

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

STATIC_ROOT = os.path.join(BASE_DIR, "static_cdn")

index.html
{% load staticfiles %}
`<link rel='stylesheet' href='{% static "css/style.css" %}' type='text/css'>`

当我运行它时collectstatic,它收集了style.css.

当我检查元素并打开 的链接时style.css (http://127.0.0.1:8000/static/css/style.css),它会给我not found消息。

我尝试对路径进行硬编码,style.css但是没有运气。

我创建了另一个示例项目并遵循相同的步骤并style.css成功加载。当我检查元素并打开 的链接时style.css,它会显示 html 代码。

我真的很无奈。非常感谢任何帮助。

编辑

setting.py template settings:

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
        ],
    },
},

]

目录结构:

 |myproject
  |----- MyApp/
  |---- myProject/
  |---- static/ 
  |---- static_cdn/
  |----manage.py

https://github.com/prafullarkamble/UnableToLoadStyle.css/

标签: htmlcssdjangopython-2.7django-1.9

解决方案


如果我没记错的话,该collectstatic命令仅用于生产。所以收集的statifiles不会影响开发。

在您的项目结构中,路径style.css为:

Salmon/static/Salmon/style.css.

所以你应该找到带有 URL 的文件:

http://127.0.0.1:8000/static/Salmon/style.css

这应该等同{% static "Salmon/style.css" %}于您的模板。


推荐阅读