Search code examples
djangohttp-status-code-404requestcontext

RequestContext returns 404 error for my imagaes?


I stumbled on a silly situation with Django's RequestContext thing. Here is my question:

I stored all my images in my media/uploads file. In my template I'm simply using :

{% for photo in photos %}
  <a href="#"> <img src="{{gallery_root}}/{{photo.get_name}}" /></a>
{% endfor %}

My view is :

def gallery_view(request):
    photos = Photo.objects.all()
    return render_to_response('gallery/sampleGallery.html',{'photos':photos},context_instance=RequestContext(request))

In my settings file :

GALLERY_ROOT = os.path.join(MEDIA_ROOT, "media/uploads")

And i have a contextprocessor file which contains:

from django.conf import settings

def gallery_root(request):
    return {'gallery_root':settings.GALLERY_ROOT}

When I open my template, the image's path appears however the server gives 404, the path seems correct but django can not serves them.. So what's the reason that I can not see images on my template ?

The image source appears like this :

<a href="#"> <img src="/Users/imperium/Desktop/sample/media/uploads/popo.jpg" /></a>  

Solution

  • Hey there, it's probably that your media isn't being served propery. Try something like this in your urls.py file.

    # if we're in DEBUG mode, allow django to serve media
    # This is considered inefficient and isn't secure.
    from django.conf import settings
    if settings.DEBUG:
        urlpatterns += patterns('',
            (r'^media/(?P<path>.*)$', 'django.views.static.serve',
             {'document_root': settings.GALLERY_ROOT}),
        )