How to display images from database in Django
In this article, you will learn how to display images from the MySQL database using Django. In the previous post, we explained how to upload an image using Django. The uploaded image is stored in a static directory. In most applications, we may need to display an 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 application. It is secure, maintainable, portable, and scalable. The main advantages of using Django are that it has been fully loaded with common web development tasks like administration, authentication, site maps, etc. If you have not installed the Django package, please follow the Django documentation for initial setup.
These are the step-by-step instructions to display an image using Django
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');
models.py
A model is a definitive source of information about your data. Each model maps to a single database table, and each attribute represents a database field. The given model defines a gallery that has an image title and an 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"
settings.py
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 to 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 stored. We must specify a MEDIA ROOT and MEDIA URL in the settings.py file in order to utilize the media files submitted to our website.
MEDIA_ROOT = os.path.join(BASE_DIR, 'image')
MEDIA_URL = '/image/'
Create HTML Template file
Next, we have created a template directory under the 'imageapp' app, 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>
views.py
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})
urls.py
At last, we have added a path to the route page for 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-
Related Articles
Django pass variable from view to HTML templateHow to read and write a file using Django
How to fetch data from database in django
Django Export Model Data to CSV
Django serialize queryset into JSON
Django Custom User Model SignUp, Login and Logout
How to display image from database in Django
Python | Uploading images in Django
How to generate and download CSV file in Django
Django Pagination with Ajax and jQuery
Django Simple File Upload
Django ajax GET and POST request
Insert data in MySQL database from an HTML form using Django
Django bootstrap 4 form template
Windows command to create and run first Django app
Django send email on contact form submission
Python OpenCV Histogram of Color Image
Detect Specific Color From Image using Python OpenCV
Python OpenCV Histogram of Grayscale Image
Python OpenCV Overlaying or Blending Two Images