Django display images from database

I am trying to display a list of images on my development page but the only images I am getting are this white-blank image.

Here are my Django codes

settings.py

STATIC_URL = '/static/'
STATICFILES_DIRS =[os.path.join(BASE_DIR,"static")]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media_cdn')

views.py

def imgdownload(request):
    allimages = ImagefieldModel.objects.all()
    return render(request, 'main/show.html',{'images': allimages})

urls.py

urlpatterns = [
    ....
    ....
    path("show/", views.imgdownload, name="imgdownload"),
    ....
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

models.py

class ImagefieldModel(models.Model): 
    title = models.CharField(max_length = 200) 
    img = models.ImageField(upload_to = "media")

    class Meta:
        db_table = "imageupload"

show.html

{% extends "main/header.html" %}

{% load static %}
 

 {% block content %}
      <head>
        <title>Django Display Images</title>
      </head>
      <body>
          <div class="container">
          <table class="table table-striped">
              <thead>
                <tr>
                  <th>Title</th>
                  <th>Image</th>
                </tr>
              </thead>
              <tbody>
              {% for img in images %}  
                <tr>
                  <td>{{img.title}}</td>
                  <td><img src="/{{ BASIC_DIR }}/{{img.img}}" width="120"/></td>
                </tr>
                {% endfor %} 
              </tbody>
          </table>  
          </div>
      </body>
 {% endblock %}
 

I am not sure what is wrong since I have declared the MEDIA_URL correctly. Some help is much appreciated.

Upvotes: 1

Views: 4968

Answers (2)

Vaishnav A V
Vaishnav A V

Reputation: 11

Try to modify show.html setting image source as:

src="{{img.img.url}}" //will link back to the image file

Upvotes: 1

Anthony
Anthony

Reputation: 959

{% for img in images %}
<img src="{{ img.img.url }}" width="120"/> 
{% endfor %}

Upvotes: 0

Related Questions