2

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

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

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:

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:

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:

list_display = ('admin_image', ...)

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

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.

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

EDIT:

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

Added the following to my 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:

absolute/filesystem/path/to/images

And in settings.py set MEDIA_URL:

/images/
Roger
  • 4,737
  • 4
  • 43
  • 68

1 Answers1

1

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

okm
  • 23,575
  • 5
  • 83
  • 90
  • Thanks. The url looks good now: http://localhost:8000/images/properties/house.jpeg however the image is still not displaying. I noticed that your second link uses an ImageField for an image where I use a FileField. I read that ImageFields require additional libraries to install which I have not done. Is it required to use ImageField to display images in Django or is the fact that the images do not display caused by something else? – Roger Dec 18 '12 at 16:13
  • @Roger ImageField works w/ image file better because it would bring image-specific clean and attributes such as 'width' and 'height'. Thus keep using ImageField for image file instead of using FileField if there is no special reason. For the 404 issue, have you configured devserver to serve media files in MEDIA_URL? Because devserver does not automatically serves media files otherwise static files. – okm Dec 18 '12 at 16:25