向djang添加静态图像

2024-03-28 18:11:13 发布

您现在位置:Python中文网/ 问答频道 /正文

已更新我的文件夹结构如下: 在运行manage.py collectstatic coomand之后,django的静态文件被复制到我的项目文件夹中,如下所示,然后我将logo.png放到它的img/

 mysite_new/

      manage.py
      mysite/
      ------ __init__.py
             urls.py
             setting.py
             wsgi.py
             templates/
                      default.html
             static/
                     img/
                          logo.png
                          .....
      ticket/
      ------__init__.py
            models.py
            view.py
            urls.py
            ......

在seting.py中,我设置了

PROJECT_PATH = os.path.abspath(os.path.dirname(__file__))
MEDIA_URL = ''
MEDIA_ROOT = ''
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(PROJECT_PATH,'static')
STATICFILES_DIRS = (
)
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

在mysite/url.py中设置

        urlpatterns = patterns('',
    url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^hello/', hello),
    url(r'^static/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT },name="media"),



)

默认.html

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8>
<title>staitc sample</title>
</head>
<body>
    <img src="{{ STATIC_URL }}img/logo.png"" alt="hahhaa">
</body>
</html>

在ticket/view.py中

def hello(request):
     return render_to_response( 'admin/default.html')

然后在web浏览器中,在输入http://127.0.0.1:8000/hello中,显示enter image description here

然后我从“哈哈”中加载图像,它链接到 enter image description here

未显示图片,因此可能图像路径不正确,并且图像未成功加载。 谁能帮我用hello-method-of-view.py显示这张图片? 这个问题让我困惑了很久,谢谢你的帮助。 我的django版本是1.4。

我已经找到了解决方案,无需移动我的静态文件夹,只需将其与ticket/保持同一级别,然后在setting.py中添加ADMIN_MEDIA_PREFIX='/static/ADMIN/'


Tags: pathdjangopy文件夹urlhelloimgadmin