RequestContext returns 404 error for my imagaes?

296 views Asked by At

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>  
2

There are 2 answers

0
darren On BEST ANSWER

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}),
    )
0
dcrosta On

MEDIA_ROOT is the filesystem path to your media, not the URL path. Building on the suggestion from mongoose_za, your template should look like:

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

Of course, you can define a new constant in settings.py which corresponds to the URL root you've chosen, and use this both in urls.py as well as in your templates.