[Answer]-Display image from model to template Django

1👍

Given:

MEDIA_URL = '/media/'

And the following template code:

<img src="{{MEDIA_URL}}/{{pic}}" alt="Profile Picture" width="200"/>

The image src couldn’t possibly be /upload/Desert.jpg. The path should be starting with /media/. More likely than not MEDIA_URL is undefined and the value of pic is upload/Desert.jpg. If that’s the case, then you’re probably missing the media template context processor. Change TEMPLATE_CONTEXT_PROCESSORS to:

TEMPLATE_CONTEXT_PROCESSORS = (
    ...
    'django.core.context_processors.media',
)

That will make MEDIA_URL available in your template context. Then, you’ll also need to remove the slash after it, or you’ll end up with two (MEDIA_URL ends with a slash), i.e.:

Instead of:

{{ MEDIA_URL }}/{{ pic }}

Use:

{{ MEDIA_URL }}{{ pic }}

UPDATE

If you’re still not getting a value for MEDIA_URL, then you’re probably not using RequestContext. You have to wrap your view’s context in RequestContext in order for the template context processors to do their thing.

If you’re using render_to_response, then:

return render_to_response('template.html', { ... context here ... }, context_instance=RequestContext(request))

If you’re using Django 1.3+, you can just use the render method, which will do this for you automatically:

return render('template.html', { ... context here ... })

0👍

In settings, this didn’t work for me,

TEMPLATE_CONTEXT_PROCESSORS = (
    ...
    'django.core.context_processors.media',
)

Instead of django.core.... I used django.template....

TEMPLATE_CONTEXT_PROCESSORS = (
    ...
    'django.template.context_processors.media',
)

Leave a comment