Cannot load Images from Django ImageField in Template

3.5k views Asked by At

I have a project developed with Django in which users have the ability to upload an image through a form in a view. That part seems to be working correctly in that I can bind the data to a form and save the image in a designated folder within the directory that I'm using for the project's database. However when I go to render a page, I get something similar to the following line (the uploaded image has the filename "2220.jpg"):

GET http://localhost:8000/Users/.../project/database/user_uploads/08-30/2220.jpg 404 (NOT FOUND) 

Here's the line in my template that renders the image:

<img class="image" src="{{ entry.image.url }}"/>

The relevant parts of my settings.py:

PROJECT_DIR = os.getcwd()
MEDIA_ROOT = os.path.join(PROJECT_DIR, 'database', 'user_uploads')
MEDIA_URL = ''
STATIC_ROOT = ''
STATIC_URL = '/static/'

The model containing the image:

def getImagePath(instance, filename):
"""Generates a path to save the file. These are timestamped by the
current date and stored in the databases directory.

Returns:
    Path for the file.
"""
date = datetime.date.today().strftime('%Y-%m-%d')
return os.path.join(
    os.getcwd(), 'database', 'user_uploads', date, filename)

class Entry(models.Model):
    # Other code omitted
    image = models.ImageField(upload_to=getImagePath)

I'm guessing there's some URL configuration I'm missing because it seems like it's asking for the image to be served via localhost (or more generally my host name) rather than just a directory on the filesystem. The file location is correct, it just seems to be executing an HTTP request for it instead of just getting it directly. What am I missing? I'm happy to provide any additional information for clarity.

Thank you in advance!

2

There are 2 answers

0
montiniz On BEST ANSWER
0
drodman On

In addition to montiniz's answer, the following thread helped me out:

Django MEDIA_URL and MEDIA_ROOT

Basically what I was missing was the URL configuration for serving files from MEDIA_ROOT. One other thing is that calling the url() parameter on a Django ImageField returns the fully qualified URL name - that is, the file's full location. All you need to serve the image from the template is its location within MEDIA_ROOT. In my case, this setting was 'database/user_uploads' and the image was located at '2013-09-02/images/2220.jpg'.

Therefore the url I needed was:

'localhost:8080/media/database/user_uploads/2013-09-02/images/2220.jpg'.

Hope this helps anyone with the same issue!