【问题标题】:Unable to load style.css in Django 1.9无法在 Django 1.9 中加载 style.css
【发布时间】:2019-02-26 02:42:23
【问题描述】:

我正在尝试在我的页面上加载 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/

【问题讨论】:

  • 这是在开发中(运行manage.py runserver?)还是在生产中?如果它正在生产中,请显示您的服务器配置(例如 apache/nginx)。你跑collectstatic了吗? style.css 文件在您的磁盘上的什么位置?
  • @Alasdair 它正在开发中。我确实跑了collectstaticstyle.css 位于BASE_DIR\static\css
  • 你能显示你的模板设置吗?
  • @root-kidz 模板加载正常。它只是style.css 没有加载。更新了问题
  • 您能发布一下您的文件夹是如何组织的吗?

标签: html css django python-2.7 django-1.9


【解决方案1】:

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

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

Salmon/static/Salmon/style.css

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

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

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

【讨论】:

  • 感谢您的回答。我将style.css 放在BASE_DIR\static 文件夹中,但这并没有帮助,所以我将它保存在myapp\static\myappname\style.css 中,但是,没有运气。
  • 如果您的文件位于myapp\static\myappname\style.css,您应该在模板中使用http://127.0.0.1:8000/static/myappname/style.css{% static "myappname/style.css" %} 访问它。
  • 我应该达到它,但是http://127.0.0.1:8000/static/Salmon/style.css 给了我url not found
【解决方案2】:

1) 选择您希望收集静态资产的文件夹来自

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "i_will_collect_from_here"),
    ... yet another folder
]

2) 选择您希望收集静态资产的文件夹:

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

3) 运行python manage.py collectstatic

注意:

STATICFILES_DIRS你可以添加任何你想要的路径,它可以是绝对路径。 collectstatic 将把静态放在你的STATIC_ROOT 中。

STATICFILES_DIRS = [
    '/var/www/assets/bootstrap/'
    ...
]

【讨论】:

  • 感谢您的回答。我希望从BASE_DIR\static 收集文件并在BASE_DIR\static_cdn 收集文件。当我运行collectstatic 时,我可以看到它在static_cdn 中收集style.css,但是它不会在页面上呈现。我在浏览器的控制台/网络选项卡中得到not found
猜你喜欢
  • 2016-07-12
  • 2017-07-01
  • 2022-09-24
  • 2016-04-07
  • 2021-02-14
  • 2016-08-09
  • 2020-12-02
  • 1970-01-01
  • 2016-04-08
相关资源
最近更新 更多