1

我已经阅读了有关图像的其他问题,但我仍然无法解决我的问题:(这可能是一些基本的东西,因为我是 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' object has no attribute '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'
4

1 回答 1

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 中的情况一样)
于 2012-05-16T19:46:28.420 回答