【问题标题】:How to load a static file in django2.0django2.0如何加载静态文件
【发布时间】:2018-10-21 17:01:27
【问题描述】:

我在 django2.0(来自 django1.4)中加载静态文件有困难。这是我目前所拥有的:

# urls.py
if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

# settings.py
TEMPLATES = [
            ...
            'builtins': [
              'django.contrib.staticfiles.templatetags.staticfiles',
             ],
]
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
STATIC_URL = '/static/'
STATIC_ROOT = ''
STATICFILES_DIRS = [
  os.path.join(SITE_ROOT, "static"),    
]

我有一张图片位于:

[my_project_root]/static/img/image.png

现在,如果我直接访问 url,我会得到 404:

http://localhost:8000/static/img/image.png

此外,如果我“通过模板”执行此操作,我还会得到 404:

{% load static %}
<img src="{% static 'img/image.png' %}" alt="My image">

我需要在此处添加什么来提供静态文件?

【问题讨论】:

  • SITE_ROOT 的值是多少?你确定文件位于project_root/static/img
  • @Lemayzeur -- 应该没问题:SITE_ROOT = os.path.dirname(os.path.realpath(__file__))。它适用于我的 templates 和其他当前使用它的项目。
  • 你在使用内置的 Django 网络服务器吗?
  • @PankajSharma 是的。
  • 您确定文件位于project_root/static/img

标签: python django django-templates


【解决方案1】:

这是一个棘手的设置。我需要将STATIC_ROOT 更改为:

STATIC_ROOT = 'static/'

否则,使用STATIC_ROOT = '',它将在[project_root]/img/image.png 中查找img 文件。

【讨论】:

    猜你喜欢
    • 2021-05-28
    • 1970-01-01
    • 1970-01-01
    • 2018-10-06
    • 1970-01-01
    • 2019-08-31
    • 2015-03-10
    • 2014-11-12
    • 2021-04-03
    相关资源
    最近更新 更多