How to display image from database in Django

Theory of Computation
In this article, you will learn how to display images from the MySQL database using Django. In the previous post, we have explained how to upload an image using Django. The uploaded image is stored into a static directory. In most of the applications, we may need the display image somewhere in the application. Django comes with pre-defined packages and methods that make this task easier.
Django is a free, open-source python-based framework. It enables fast development of any type of web applications. It is secure, maintainable, portable and scalable. The main advantages of using Django are that it has fully loaded common web development tasks, like administration, authentication, site maps etc. If you had not installed the Django package, please follow the Django documentation for initial setup.
Suppose we have the following MySQL table 'gallery' -
CREATE TABLE IF NOT EXISTS `gallery` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` char(200) NOT NULL,
  `img` varchar(200) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=12 DEFAULT CHARSET=utf8;
INSERT INTO `gallery` (`id`, `title`, `img`) VALUES
(9, 'Flowers', 'media/flowers.jpg'),
(10, 'Deer', 'media/deer.jpg'),
(11, 'Cat', 'media/cat.jpg');
A model is a definitive source of information about your data. Each model maps a single database table and each attribute represents a database field. The given model defines a gallery which has an image title and image source.
from django.db import models

class GetImage(models.Model):   
    title = models.CharField(max_length=100)
    img = models.ImageField(upload_to="media")
    class Meta:
        db_table = "gallery"
First, configure the database. We need to tell Django we're going to use the MySQL database. Do this by editing your settings file and changing the DATABASES setting to add the name of the database with configurations.
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'demo',
        'USER': 'root',
        'PASSWORD': '',
        'HOST': 'localhost',
        'PORT': '3306'
    }
}
Also, add the following codes in your settings file. MEDIA_URL is the URL that will serve the media files and MEDIA_ROOT is the path to the root directory where the files are getting stored.
MEDIA_ROOT =  os.path.join(BASE_DIR, 'image') 
MEDIA_URL = '/image/'
Next, we have created a template directory under 'imageapp' app and where we have created an HTML template file 'show.html' that calls on the browser for displaying images.
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Django Display Images</title>
  <meta charset="utf-8">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</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>
</html>
We have placed the following code in 'views.py'.
from django.shortcuts import render,redirect
from imageapp.models import GetImage 

# Create your views here.
def display_images(request): 
  
    # getting all the objects of hotel. 
    allimages = GetImage.objects.all()  
    return render(request, 'show.html',{'images' : allimages})

At last, we have added a path to the route page to the particular link. Make sure you've got your MEDIA_URL and MEDIA_ROOT correct in your settings.py then you can append the following to your url conf -
from django.contrib import admin
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from imageapp import views

urlpatterns = [
    path('show', views.display_images),
]

if settings.DEBUG:
        urlpatterns += static(settings.MEDIA_URL,
                              document_root=settings.MEDIA_ROOT)
When we migrate and run the application, we will get the result something like this -

Jan 3
Stateful vs Stateless
A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities...

A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities...

Dec 29
Best programming language to learn in 2021
In this article, we have mentioned the analyzed results of the best programming language for 2021...

In this article, we have mentioned the analyzed results of the best programming language for 2021...

Dec 20
How is Python best for mobile app development?
Python has a set of useful Libraries and Packages that minimize the use of code...

Python has a set of useful Libraries and Packages that minimize the use of code...

July 18
Learn all about Emoji
In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more...

In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more...

Jan 10
Data Science Recruitment of Freshers
In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician...

In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician...






eTutorialsPoint©Copyright 2016-2022. All Rights Reserved.