Django admin中的图像是使用错误的URL生成的

时间:2022-09-03 21:22:04

I'm trying out Django and ran into the following problem:

我正在尝试Django并遇到以下问题:

I have a model class Property which has various attributes amongst which is an image. The image property is defined as:

我有一个模型类Property,它有各种属性,其中包括一个图像。 image属性定义为:

image = models.FileField(
    upload_to = 'properties',
    default = 'properties/house.jpeg')

The directory properties is a sub directory of images which is defined in settings.py as:

目录属性是图像的子目录,在settings.py中定义为:

MEDIA_ROOT = '/Users/.../Development/pms/images/'
MEDIA_URL = 'http://localhost:8000/images/'

Derived from similar posts on SO regarding this topic, I added the following to my Property model:

从SO上有关此主题的类似帖子中得出,我将以下内容添加到我的Property模型中:

def admin_image(self):
    return '<img src="images/%s" width="100"/>' % self.image
admin_image.allow_tags = True

I then added admin_image() as a property to the list display:

然后我将admin_image()作为属性添加到列表显示中:

list_display = ('admin_image', ...)

When I check the URL for the image in the admin application, I get the following:

当我在管理应用程序中检查图像的URL时,我得到以下内容:

http://127.0.0.1:8000/admin/properties/property/images/properties/house.jpeg/

This generates a 404 as the URL is generated incorrectly. Firstly the path is incorrect and secondly there's a trailing / at the end of the URL.

这会生成404,因为URL生成不正确。首先路径不正确,其次是URL的末尾/尾部。

I'm obviously missing something... What do I do wrong?

我显然错过了什么......我做错了什么?

EDIT:

Thanks to @okm for the various pointers. I did the following:

感谢@okm的各种指针。我做了以下事情:

Added the following to my urls.py:

在我的urls.py中添加了以下内容:

from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf import settings

... original url patterns ...

urlpatterns += staticfiles_urlpatterns()

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

Then in settings.py set MEDIA_ROOT:

然后在settings.py中设置MEDIA_ROOT:

absolute/filesystem/path/to/images

And in settings.py set MEDIA_URL:

在settings.py中设置MEDIA_URL:

/images/

1 个解决方案

#1


1  

According to the doc & here, try self.image.url instead of '...' % self.image

根据doc&here,尝试使用self.image.url而不是'...'%self.image

#1


1  

According to the doc & here, try self.image.url instead of '...' % self.image

根据doc&here,尝试使用self.image.url而不是'...'%self.image