【问题标题】:Django: Image from static folder doesn't loadDjango:来自静态文件夹的图像不加载
【发布时间】:2020-10-21 04:43:28
【问题描述】:

我需要帮助=)

静态文件夹中的图片无法加载。

版本:Django 1.11.3

这是我的代码:

first_project/first_project/settings.py:

import os
 
 
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
 
TEMPLATE_DIR=os.path.join(BASE_DIR,"templates")
STATIC_DIR=os.path.join(BASE_DIR,"static")
 
...
 
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'first_app',
]
 
...
 
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
 
STATIC_URL = '/static/'
STATICFILES_DIRS=[
    STATIC_DIR,
    os.path.join(BASE_DIR,"first_app","static","first_app"),
]

first_project/templates/first_app/index.html:

<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Yp</title>
</head>
<body>
<h1>This is yp picture!</h1>
<!--It works -->
<img src="/static/first_app/yp.jpg" alt="oh oh">
<!--It doesn't work-->
<img scr="{% static "first_app/yp.jpg" %}" alt="oh oh">
 
</body>
</html>

first_project/static/first_app/yp.jpg - 图片的路径。

谢谢!

【问题讨论】:

  • 为什么是Django 1.11.3?其 LTS 版本于 2020 年 4 月达到 EOL

标签: django django-templates django-settings django-static


【解决方案1】:

你应该做几件事,但我认为你没有 这样做。

我创建了一个简单的项目只为你并添加到我的 GitHub

只需点击此链接:GitHub first Project templates

如果有帮助,请投票。

【讨论】:

    【解决方案2】:

    首先,您写的是 scr,而不是 src,这应该更正。

        <!--It doesn't work-->
    <img scr="{% static "first_app/yp.jpg" %}" alt="oh oh">
    

    之后,您可能需要从代码中清除“first_app/”部分,因为您直接在设置文件中处理您的目录。

    【讨论】:

    • 非常感谢=)) "scr" 而不是 "src" =) 我是个笨蛋)
    • @delka 很高兴能帮助您。最好的问候!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-08
    • 2014-10-31
    • 2018-09-01
    • 2022-08-15
    相关资源
    最近更新 更多