gpt4 book ai didi

python - 如何在Django项目中添加图片

转载 作者:行者123 更新时间:2023-11-28 17:45:42 25 4
gpt4 key购买 nike

我在 Django 项目中添加图像时遇到问题,我的项目是

my_app
manage.py
my_app
urls.py
views.py
settings.py
templates
home.html
static
img
image1.png

settings.py

都是默认设置的

STATIC_URL = '/static/'

home.html 我添加了代码

{% load staticfiles %}

<img src="{% static 'img/image1.png' %}" />

但是无法加载图片,找不到页面

127.0.0.1:1000/static/img/openicon2.png

Page not found (404)
Request Method: GET
Request URL: 127.0.0.1:1000/static/img/openicon2.png

有人可以帮助我吗?也许我需要修改 urls.py

最佳答案

根据我的经验,我在 settings.py 中完成了以下操作,一切正常

import os.path,sys
CURRENT_DIR = os.path.dirname(__file__).replace('\\','/')
PROJECT_ROOT = os.path.abspath(os.path.join(CURRENT_DIR, os.pardir))

# other codes and stuff

我添加了一个名为 deveop 的变量,并根据我的应用程序是在开发服务器还是 apache 上运行来更改它

DEVELOP = True

# other codes and stuff

if DEVELOP == False:
MEDIA_ROOT = os.path.join(PROJECT_ROOT,'media')

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = '/media/'

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
if DEVELOP == False:
STATIC_ROOT = os.path.join(PROJECT_ROOT,'static')

# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/static/'

# Additional locations of static files
STATICFILES_DIRS = (
os.path.join(PROJECT_ROOT,'static'),
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)

关于python - 如何在Django项目中添加图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18611114/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com