3

我在 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

4

2 回答 2

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

我添加了一个名为 devop 的变量,我更改它取决于我的应用程序是在开发服务器上运行还是在 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.
)
于 2013-09-04T11:49:39.517 回答
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)

然后你可以动态添加图像!

在模板中:

<img ... src="{{key.image.url}}" ... >
于 2019-10-22T18:08:29.973 回答