Django模板 - 不显示动态图像

时间:2012-05-15 22:19:28

标签: django image django-templates

我已经阅读了有关图像的其他问题,但我仍然无法解决我的问题:(这可能是基本的,因为我是django的新手。

所以我有模型示例:

class Example(models.Model):
    image = models.ImageField(upload_to = "examples/")

我想在模板中显示它。作为一个视图,我使用通用的detailView。这部分与模板图像有关:

<p>Image: <img src="{{ example.image.url }}"/></p>

我更改了我的settings.py:

MEDIA_ROOT = '/home/nicpon/Dokumenty/aplikacje/images/'
MEDIA_URL = '/images/'

此时站点没有图像显示(在图像无法显示时显示的是正方形)

现在我也更改了urls.py:`

if settings.DEBUG:
    urlpatterns += patterns('', url(r'^images/(?P<path>.*)$',
    'django.views.static.serve', {'document_root': settings.MEDIA_ROOT})),    

但导致错误:“'list'对象在每个页面上都没有'resolve'”。

编辑: 当我将{{example.image.url}}放在img标签之外时,它会显示/images/exapmles/specific_image.jpg 我计算机上该图像的目录是/home/nicpon/Dokumenty/aplikacje/images/examples/specific_image.jpg

追溯:

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/images/examples/sepcific_image.jpg

Django Version: 1.4
Python Version: 2.6.5
Installed Applications:
('django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.admin',
 'example',
 'registration')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware')


Traceback:
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response
  89.                     response = middleware_method(request)
File "/usr/local/lib/python2.6/dist-packages/django/middleware/common.py" in process_request
  67.             if (not urlresolvers.is_valid_path(request.path_info, urlconf) and
File "/usr/local/lib/python2.6/dist-packages/django/core/urlresolvers.py" in is_valid_path
  531.         resolve(path, urlconf)
File "/usr/local/lib/python2.6/dist-packages/django/core/urlresolvers.py" in resolve
  420.     return get_resolver(urlconf).resolve(path)
File "/usr/local/lib/python2.6/dist-packages/django/core/urlresolvers.py" in resolve
  300.                     sub_match = pattern.resolve(new_path)

Exception Type: AttributeError at /images/examples/specific_image.jpg
Exception Value: 'list' object has no attribute 'resolve'

1 个答案:

答案 0 :(得分:2)

尝试做类似这样的事情是你的settings.py:

MEDIA_SERVER_URL = 'http://www.example.com/'
MEDIA_URL = os.path.join(MEDIA_SERVER_URL, 'images/')

然后再做

src="{{ MEDIA_URL }}{{ example.image.url }}"

同时检查权限:

  1. 媒体目录(/ home / nicpon / Dokumenty / aplikacje / images /):应允许您的网络服务器阅读(例如:chgrp www-data images)
  2. 您的网络服务器应配置为正确处理媒体服务。理想情况下,可以使用单独的媒体服务器,但如果您使用django为媒体提供服务,则应检查相应的URL(如urls.py中的情况)