etutorialspoint
  • Home
  • PHP
  • MySQL
  • MongoDB
  • HTML
  • Javascript
  • Node.js
  • Express.js
  • Python
  • Jquery
  • R
  • Kotlin
  • DS
  • Blogs
  • Theory of Computation

How to display image 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 fully loaded 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 utilise 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 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>




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 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-

Django display images



Related Articles

Django pass variable from view to HTML template
How 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




Most Popular Development Resources
Retrieve Data From Database Without Page refresh Using AJAX, PHP and Javascript
-----------------
PHP Create Word Document from HTML
-----------------
How to get data from XML file in PHP
-----------------
Hypertext Transfer Protocol Overview
-----------------
PHP code to send email using SMTP
-----------------
Characteristics of a Good Computer Program
-----------------
How to encrypt password in PHP
-----------------
Create Dynamic Pie Chart using Google API, PHP and MySQL
-----------------
PHP MySQL PDO Database Connection and CRUD Operations
-----------------
Splitting MySQL Results Into Two Columns Using PHP
-----------------
Dynamically Add/Delete HTML Table Rows Using Javascript
-----------------
How to get current directory, filename and code line number in PHP
-----------------
How to add multiple custom markers on google map
-----------------
Get current visitor\'s location using HTML5 Geolocation API and PHP
-----------------
Fibonacci Series Program in PHP
-----------------
How to Sort Table Data in PHP and MySQL
-----------------
Simple star rating system using PHP, jQuery and Ajax
-----------------
How to generate QR Code in PHP
-----------------
Simple pagination in PHP
-----------------
Submit a form data using PHP, AJAX and Javascript
-----------------
PHP MYSQL Advanced Search Feature
-----------------
jQuery loop over JSON result after AJAX Success
-----------------
Recover forgot password using PHP7 and MySQLi
-----------------
PHP Server Side Form Validation
-----------------
PHP user registration and login/ logout with secure password encryption
-----------------
jQuery File upload progress bar with file size validation
-----------------
To check whether a year is a leap year or not in php
-----------------
Simple File Upload Script in PHP
-----------------
Php file based authentication
-----------------
Simple PHP File Cache
-----------------
PHP User Authentication by IP Address
-----------------
Calculate distance between two locations using PHP
-----------------
PHP Secure User Registration with Login/logout
-----------------
Polling system using PHP, Ajax and MySql
-----------------
How to print specific part of a web page in javascript
-----------------
Detect Mobile Devices in PHP
-----------------
Simple Show Hide Menu Navigation
-----------------
Simple way to send SMTP mail using Node.js
-----------------
SQL Injection Prevention Techniques
-----------------
Get Visitor\'s location and TimeZone
-----------------
Preventing Cross Site Request Forgeries(CSRF) in PHP
-----------------
PHP Sending HTML form data to an Email
-----------------
Google Street View API Example
-----------------
Driving route directions from source to destination using HTML5 and Javascript
-----------------
Date Timestamp Formats in PHP
-----------------
CSS Simple Menu Navigation Bar
-----------------
PHP Programming Error Types
-----------------
Convert MySQL to JSON using PHP
-----------------
Set and Get Cookies in PHP
-----------------
How to add google map on your website and display address on click marker
-----------------
How to select/deselect all checkboxes using Javascript
-----------------
PHP Getting Document of Remote Address
-----------------
How to display PDF file in web page from Database in PHP
-----------------
File Upload Validation in PHP
-----------------
PHP FTP Connection and File Handling
-----------------


Most Popular Blogs
Most in demand programming languages
Best mvc PHP frameworks in 2019
MariaDB vs MySQL
Most in demand NoSQL databases for 2019
Best AI Startups In India
Kotlin : Android App Development Choice
Kotlin vs Java which one is better
Top Android App Development Languages in 2019
Web Robots
Data Science Recruitment of Freshers - 2019


Interview Questions Answers
Basic PHP Interview
Advanced PHP Interview
MySQL Interview
Javascript Interview
HTML Interview
CSS Interview
Programming C Interview
Programming C++ Interview
Java Interview
Computer Networking Interview
NodeJS Interview
ExpressJS Interview
R Interview


Popular Tutorials
PHP Tutorial (Basic & Advance)
MySQL Tutorial & Exercise
MongoDB Tutorial
Python Tutorial & Exercise
Kotlin Tutorial & Exercise
R Programming Tutorial
HTML Tutorial
jQuery Tutorial
NodeJS Tutorial
ExpressJS Tutorial
Theory of Computation Tutorial
Data Structure Tutorial
Javascript Tutorial




General Knowledge

listen
listen
listen
listen
listen
listen
listen
listen
listen


Learn Popular Language

listen
listen
listen
listen
listen

Blogs

  • Jan 3

    Stateful vs Stateless

    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...

  • 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...

  • 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...

  • 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...

Follow us

  • etutorialspoint facebook
  • etutorialspoint twitter
  • etutorialspoint linkedin
etutorialspoint youtube
About Us      Contact Us


  • eTutorialsPoint©Copyright 2016-2022. All Rights Reserved.