Question

So far I made it to the part where a user uploads an image but how can I use those images which are located in my media folder? Here is what I tried :

my view:

#I even tried to import MEDIA_ROOT to use it in my template...
#from settings import MEDIA_ROOT

def home(request):
    latest_images = Image.objects.all().order_by('-pub_date')
    return render_to_response('home.html',
                             #{'latest_images':latest_images, 'media_root':MEDIA_ROOT},
                             {'latest_images':latest_images,},
                             context_instance=RequestContext(request)
                             )

my model:

class Image(models.Model):
    image = models.ImageField(upload_to='imgupload')
    title = models.CharField(max_length=250)
    owner = models.ForeignKey(User)
    pub_date = models.DateTimeField(auto_now=True)

my template:

{% for image in latest_images %}
    <img src="{{ MEDIA_ROOT }}{{ image.image }}" width="100px" height="100px" />
{% endfor %}

and my settings.py MEDIA_ROOT and URL:

MEDIA_ROOT = '/home/tony/Documents/photocomp/photocomp/apps/uploading/media/'
MEDIA_URL = '/media/'

So again here is what I am trying to do: Use those images in my templates!

Was it helpful?

Solution

On development machine, you need to tell the devserver to serve uploaded files

# in urls.py
from django.conf import settings

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

{# in template, use sorl-thumbnail if your want to resize images #}
{% with image.image as img %}
<img src="{{ img.url }}" width="{{ img.width }}" height="{{ img.height }}" />
{% endwith %}

# furthermore, the view code could be simplified as
from django.shortcuts import render
def home(request):
    latest_images = Image.objects.order_by('-pub_date')
    return render(request, 'home.html', {'latest_images':latest_images})

On production environment using normal filesystem storage, ensure the webserver has permission to write to MEDIA_ROOT. Also configure the webserver to read /media/filename from correct path.

OTHER TIPS

If you use the url attribute, MEDIA_URL is automatically appended. Use name if you want the path without MEDIA_URL. So all you need to do is:

<img src="{{ some_object.image_field.url }}">

ImageField() has an url attribute so try:

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

You could also add a method to your model like this to skip the MEDIA_ROOT part:

from django.conf import settings

class Image(...):

    ...

    def get_absolute_url(self):
        return settings.MEDIA_URL+"%s" % self.image.url

Also I'd use upload_to like this for sanity:

models.ImageField(upload_to="appname/classname/fieldname")

Try these settings:

import socket

PROJECT_ROOT = path.dirname(path.abspath(__file__))

# Dynamic content is saved to here
MEDIA_ROOT = path.join(PROJECT_ROOT,'media')

if ".example.com" in socket.gethostname():
    MEDIA_URL = 'http://www.example.com/media/'
else:
    MEDIA_URL = '/media/'

# Static content is saved to here
STATIC_ROOT = path.join(PROJECT_ROOT,'static-root') # this folder is used to collect static files in production. not used in development
STATIC_URL =  "/static/"
STATICFILES_DIRS = (
    ('', path.join(PROJECT_ROOT,'static')), #store site-specific media here.
)

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

For Django version 2.2., try the following:

#You need to add the following into your urls.py  
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
Your URL mapping
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) #add this  

# And then use this in your html file to access the uploaded image
<img src="{{ object.image_field.url }}">

You have to make the folder containing the uploaded images "web accessible", i.e. either use Django to serve static files from the folder or use a dedicated web server for that.

Inside your template code, you have to use proper MEDIA_URL values.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top