我在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
?
答案 0 :(得分:1)
根据我的经验,我在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.
)
答案 1 :(得分:1)
只需添加
在settings.py中:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
在项目的urls.py中:
from django.conf.urls.static import static
from my_app import settings
urlpatterns = [.....]+static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT)
然后您可以动态添加图像!
在Templets中
<img ... src="{{key.image.url}}" ... >