Keerthan Bhat
Keerthan Bhat

Reputation: 324

Displaying images in django template

I am querying images from the database and displaying them in HTML.

My views.py is

@login_required
def viewall(request):
    context = RequestContext(request)
    images = Images.objects.all().order_by('-id')
    return render_to_response('cms/view-all.html',{'images':images,'media_url':settings.MEDIA_URL},context)

My view-all.html is

{% extends "cms/base.html" %}

{% block title %}
    View-all
{% endblock %}

{% block main %}

{%  for image in images %}
    <img src="{{ media_url }}{{ image.file }}">
{% endfor %}
{% endblock %}

In settings.py

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(PROJECT_PATH, 'media')

My images are in the project directory file /media/images.

But the images aren't getting displayed. I'm getting like this.

What might be the problem here?

Upvotes: 0

Views: 2593

Answers (2)

K P
K P

Reputation: 874

try this, u need to add "." before path ( assuming media folder is in root directory )

MEDIA_URL = './media/'

Upvotes: 0

neverwalkaloner
neverwalkaloner

Reputation: 47354

You need to add media url to project's urlpatterns:

from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

See details here.

Upvotes: 2

Related Questions