pythondjangofile-uploaddjango-templatesmedia-url

How can I use user uploaded files in my templates? (django)


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!


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.