【问题标题】:How to view images in django html template如何在 django html 模板中查看图像
【发布时间】:2014-09-15 10:01:13
【问题描述】:

即使图片的网址是准确的,我也会不断收到 404 错误。是的,我查看了官方 django 文档和大量 stackoverflow 帖子。我无法从这些中弄清楚。如果有人能破译instructions are saying 做什么,我将不胜感激,因为他们似乎缺少信息。

index.html:

#I have tried static and staticfiles
{% load static %}
#a lot of code later...
<img border="0" src="{% static "logo.png" %}" alt="TMS" width="125" height="80">

目录结构:

projectname
    ->__init__.py, settings.py, ...
manage.py
db.sql3
app_name
    -> admin.py, models.py, views.py, templates->index.html, ...
static
    ->logo.png

我在 settings.py 和 'django.contrib.staticfiles' 中唯一关于静态的东西:

STATIC_URL = '/static/'

我的 views.py 文件具有返回 HttpResponse(t.render(c)) 的索引函数,其中 t 是 index.html 模板,c 是上下文。这些可能是问题吗?

生成的网址是这样的:http://127.0.0.1:8000/static/logo.png

【问题讨论】:

    标签: python django image static http-status-code-404


    【解决方案1】:

    您正在使用应用程序之外的静态目录(它位于项目文件夹中),因此在 settings.py 中您还需要:

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

    【讨论】:

    • 并在您的模板中使用{% load staticfiles %}
    • 天哪,它奏效了。伙计,你不知道这给我带来了多大的压力。奇怪的是,我确实在某个时候添加了该代码,但由于某种原因它现在已经工作了。谢谢。
    猜你喜欢
    • 2015-01-08
    • 2020-03-27
    • 2019-11-20
    • 2021-12-26
    • 2011-11-10
    • 1970-01-01
    • 1970-01-01
    • 2018-01-17
    • 2013-04-05
    相关资源
    最近更新 更多