The Wayback Machine - https://web.archive.org/web/20240828110716/https://www.geeksforgeeks.org/python-uploading-images-in-django/
Open In App

Python | Uploading images in Django

Last Updated : 03 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In most websites, we often deal with media data such as images, files, etc. In Django, we can deal with the images with the help of the model field which is ImageField. In this article, we have created the app image_app in a sample project named image_upload. The very first step is to add the below code in the settings.py file. 

Prerequisite – Introduction to Django 

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

MEDIA_ROOT is for server path to store files in the computer. MEDIA_URL is the reference URL for the browser to access the files over Http. In the urls.py we should edit the configuration like this

from django.conf import settings
from django.conf.urls.static import static
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)

A sample models.py should be like this, in that we have created a Hotel model which consists of hotel name and its image. In this project we are taking the hotel name and its image from the user for hotel booking website. 

Python
# models.py
 class Hotel(models.Model):
    name = models.CharField(max_length=50)
    hotel_Main_Img = models.ImageField(upload_to='images/')

Here upload_to will specify, to which directory the images should reside, by default django creates the directory under media directory which will be automatically created when we upload an image. No need of explicit creation of media directory. We have to create a forms.py file under image_app, here we are dealing with model form to make content easier to understand. 

Python
# forms.py
from django import forms
from .models import Hotel


class HotelForm(forms.ModelForm):

    class Meta:
        model = Hotel
        fields = ['name', 'hotel_Main_Img']

Django will implicitly handle the form verification’s with out declaring explicitly in the script, and it will create the analogous form fields in the page according to model fields we specified in the models.py file. This is the advantage of model form. Now create a templates directory under image_app in that we have to create a html file for uploading the images. HTML file should look like this. 

html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hotel_image</title>
</head>
<body>
    <form method = "post" enctype="multipart/form-data">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Upload</button>
    </form>
</body>
</html>

When making a POST request, we have to encode the data that forms the body of the request in some way. So, we have to specify the encoding format in the form tag. multipart/form-data is significantly more complicated but it allows entire files to be included in the data. The csrf_token is for protection against Cross-Site Request Forgeries. form.as_p simply wraps all the elements in HTML paragraph tags. The advantage is not having to write a loop in the template to explicitly add HTML to surround each title and field. In the views.py under image_app in that we have to write a view for taking requests from user and gives back some html page. 

Python
from django.http import HttpResponse
from django.shortcuts import render, redirect
from .forms import HotelForm

# Create your views here.


def hotel_image_view(request):

    if request.method == 'POST':
        form = HotelForm(request.POST, request.FILES)

        if form.is_valid():
            form.save()
            return redirect('success')
    else:
        form = HotelForm()
    return render(request, 'hotel_image_form.html', {'form': form})


def success(request):
    return HttpResponse('successfully uploaded')

whenever the hotel_image_view hits and that request is POST, we are creating an instance of model form form = HotelForm(request.POST, request.FILES) image will be stored under request.FILES one. If it is valid save into the database and redirects to success url which indicates successful uploading of the image. If the method is not POST we are rendering with html template created. urls.py will look like this – 

Python
from django.contrib import admin
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from .views import hotel_image_view

urlpatterns = [
    path('image_upload', hotel_image_view, name='image_upload'),
    path('success', success, name='success'),
]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL,
                          document_root=settings.MEDIA_ROOT)

Output: 

Now make the migrations and run the server.  When we hit the URL in the browser, in this way it looks.

 

After uploading the image it will show success.

Now in the project directory media directory will be created, an images directory will be created and the image will be stored under it. Here is the final result.

final_output-1-copy


Now we can write a view for accessing those images, for simplicity let’s take example with one image and it is also applicable for many images. 

Python
# Python program to view
# for displaying images


def display_hotel_images(request):

    if request.method == 'GET':

        # getting all the objects of hotel.
        Hotels = Hotel.objects.all()
        return render((request, 'display_hotel_images.html',
                       {'hotel_images': Hotels}))

A sample html file template for displaying images. 

html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hotel Images</title>

    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
    </script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
    </script>
</head>
<body>

    {% for hotel in hotel_images %}
            <div class="col-md-4">
                    {{ hotel.name }}
                    <img src="{{ hotel.hotel_Main_Img.url }}" class="img-responsive" style="width: 100%; float: left; margin-right: 10px;" />
            </div>
    {% endfor %}

</body>
</html>

Insert the url path in the urls.py file

# urls.py
path('hotel_images', display_hotel_images, name = 'hotel_images'),

Here is the final view on the browser when we try to access the image.

Final result in browser

Hotel Image



Previous Article
Next Article

Similar Reads

Uploading Image Using Django with Firebase
Firebase is a product of Google which helps developers to build, manage, and grow their apps easily. It helps developers to build their apps faster and in a more secure way. No programming is required on the firebase side which makes it easy to use its features more efficiently. It provides cloud storage. It uses NoSQL for the storage of data. Here
4 min read
Uploading files on Google Drive using Python
In the modern era of the internet, a large number of mundane or work-related tasks are carried out over the internet. Compromise of data stored on a device could cause massive harm to an individual/company. Considering the rise in the number of malware, viruses, worms, trojan horse etc the security of data at rest has become a concern for many peop
3 min read
Difference between Downloading and Uploading
What is Downloading : Meaning of downloading is that our computer is receiving data from the Internet. When users are copying any file from the Internet to their device (computer, mobile, etc.), they download it. Example: a browser downloads some specific web pages from the web server on the Internet. Furthermore, at the time of downloading the bro
2 min read
Google Cloud Platform - Ways of Uploading Data to GCS
Before you can harness the power of the cloud, to serve your content, you have to get your data into it. In this article, we will look into all the different ways you can upload data. We all know that Google Cloud Storage (GCS) can serve your binary assets to users worldwide at high speed and low price. But before you can do any of that, you need t
3 min read
Downloading and Uploading Files from Internet
The terms downloading and uploading are generally used while browsing the Internet. Receiving data or a file from the Internet on your computer is referred to as "downloading." Uploading refers to the process of sending data or a file from your computer to a remote location on the Internet. Remote Site: A remote site is one that is physically locat
7 min read
Servlet - Uploading File
Servlets are the Java programs that run on the Java-enabled web server or application server. They are used to handle the request obtained from the webserver, process the request, produce the response, then send a response back to the webserver. Now let us learn how to upload a file to a server in this section. In an HTML file, the method must be p
2 min read
Why would $_FILES be empty when uploading files to PHP ?
While uploading the files or writing the code, developers do many mistakes which we cannot figure out most of the time. Some spelling mistakes, some forgotten parts in the code lead to failed uploading of the file and give warnings or errors. To avoid this kind of mistake, we should learn about the common mistakes occurring for a better understandi
3 min read
Uploading a Reverse Shell to a Web Server in Kali Linux
We basically hack the webserver for gaining access to the system. We look into what is inside the web server and we want to have full control of the web server. Therefore we can download or access the uploaded content. In this article, we are using a reverse shell made with PHP. We are uploading the reverse shell into the web server and trying to h
3 min read
Uploading and Downloading Files in Flask
This article will go over how to upload and download files using a Flask database using Python. Basically, we have a section for uploading files where we can upload files that will automatically save in our database. When we upload a file and submit it, a message stating that your file has been uploaded and displaying the file name on the screen ap
7 min read
Uploading and Reading a CSV File in Flask
Flask is a flexible, lightweight web-development framework built using python. A Flask application is a Python script that runs on a web server, which listens to HTTP requests and returns responses. It is designed for simple and faster development. In this article, let's upload a CSV (Comma-Separated Values) file and read the contents of the file o
3 min read
How to Compress Image in Android Before Uploading it to Firebase Storage?
Usually, in an app we make users upload images like profile images or others. But there is a chance that the uploaded image is only for display purposes, that too in a short frame. So, these images do not have to be stored in a high-resolution format. Hence even if the user uploads a high-resolution pic, the image must be compressed before storing
4 min read
Uploading and Downloading Objects in Google Cloud Storage: Command Line and API
Cloud storage refers to storing your data in remote locations i.e., the cloud. Cloud Storage became increasingly popular in the information era. With tons of data in hand, storing them in the cloud is very affordable. By storing the data in the cloud, we can access the data at any time irrespective of the device and the location. Google Cloud Stora
7 min read
How to check the Type and Size before File Uploading in PHP ?
In PHP, it's essential to validate file types and sizes before allowing users to upload files to a server. This helps prevent potential security vulnerabilities and ensures that only allowed file types and sizes are accepted. PHP provides various methods to perform these validations, including checking file extensions, MIME types, and file sizes. A
2 min read
How to Restrict File Uploading Permission in WordPress Sites ?
Ensuring the security of your WordPress site is paramount, and one crucial aspect is restricting file upload permissions. Unrestricted file uploads can pose significant security risks, including the potential for malicious code injections or unauthorized access. These are the following ways to restrict the file uploading permission in WordPress: Ta
2 min read
Validation of file size while uploading using JavaScript / jQuery
Validation of file size while uploading is important to provide a nice user experience. In this article, we will learn how to implement file size validation by checking file size before uploading using JavaScript and jQuery. Below are both the ways: Table of Content Using JavaScriptUsing jQueryApproach 1: Using JavaScriptListen for the change event
2 min read
File uploading in React.js
File upload in React JS is an essential requirement while creating a complete application. File uploading means a user from a client machine wants to upload files to the server. For example, users can upload images, videos, etc on Facebook, and Instagram. As with any programming problem, there are many ways to achieve this outcome. This article exp
4 min read
File Type Validation while Uploading it using JavaScript
In this article, we will learn how to implement file type validation by checking file extension before uploading it using JavaScript. This is a demonstration of client-side validation and is implemented to provide a nice user experience. In some cases, client-side validation is a much better method in comparison to the server-side method as it cons
3 min read
PHP | Uploading File
Have you ever wondered how websites build their system of file uploading in PHP? Here we will come to know about the file uploading process. A question which you can come up with - 'Are we able to upload any kind of file with this system?'. The answer is yes, we can upload files with different types of extensions. Approach: To run the PHP script we
3 min read
How to implement file uploading and downloading with Express ?
File uploading and downloading are important features of a web app. Here we are going to handle file upload using express-fileupload npm package, and the download is handled using res.download() function of the express. The express-fileupload is passed to the app as the middleware. Approach: First, install express-fileupload module and then require
3 min read
JSP - File Uploading
In this article, we will learn about how to upload a file to a server using JSP. JSP stands for Java Server Pages. JSP is a server-side web technology, traditionally used to create dynamic web pages. Before that, servlets were highly used to create dynamic web pages, in that HTML tags are inserted into the Java code(in particular response print str
6 min read
File uploading in Node
File uploading involves a user requesting to upload a file from their client machine to the server. For instance, on platforms like Facebook or Instagram, users upload images, videos, etc. In this article, we'll explore how to achieve file uploads using Node.js. Features of Multer module:The file can be uploaded to the server using the Multer modul
4 min read
Preview an image before uploading using jQuery
Previewing an image before uploading using jQuery allows users to see the selected image on the webpage before submitting it to the server. This enhances user experience by providing immediate visual feedback, ensuring the correct image is chosen. There are several methods to preview an image before uploading it to the server using JQuery which are
4 min read
Arithmetic Operations on Images using OpenCV | Set-2 (Bitwise Operations on Binary Images)
Prerequisite: Arithmetic Operations on Images | Set-1Bitwise operations are used in image manipulation and used for extracting essential parts in the image. In this article, Bitwise operations used are : ANDORXORNOT Also, Bitwise operations helps in image masking. Image creation can be enabled with the help of these operations. These operations can
4 min read
Bootstrap 5 Images Aligning Images
Bootstrap 5 Aligning Images are used to set the alignment to the image. We will use float or text alignment classes to set the alignment of images. We can use the .mx-auto margin utility class to center the block-level images. Aligning Images used Classes: .float-start: This class is used to set the position of an element to left..float-end: This c
2 min read
Can ChatGPT Generate Images? How to Create Images Using ChatGPT
In the rapidly evolving world of artificial intelligence, ChatGPT has become a household name for its ability to generate human-like text. But did you know that it can also create stunning images? This feature of ChatGPT has become a hot topic in the year 2024. AI image generation is not just a futuristic concept, it's here and now. OpenAI's DALL-E
8 min read
Bootstrap 5 Images Responsive images
Bootstrap 5 Responsive images are used to resize the images according to their parent element and screen sizes. It means, the size of the image should not overflow its parent element and will grow and shrink according to the change in the size of its parent without losing its aspect ratio. Responsive images using Class:.img-fluid: This class is use
1 min read
Adding Tags Using Django-Taggit in Django Project
Django-Taggit is a Django application which is used to add tags to blogs, articles etc. It makes very easy for us to make adding the tags functionality to our django project.Setting up Django Project Installing django-taggit pip install django-taggitADD it to Main Project's settings.py file C/C++ Code INSTALLED_APPS = [ 'django.contrib.admin', 'dja
2 min read
How to customize Django forms using Django Widget Tweaks ?
Django forms are a great feature to create usable forms with just few lines of code. But Django doesn't easily let us edit the form for good designs. Here, we will see one of the ways to customize Django forms, So they will look according to our wish on our HTML page. Basically we will check the methods to include our own custom css, classes, or id
3 min read
Styling Django Forms with django-crispy-forms
Django by default doesn't provide any Django form styling method due to which it takes a lot of effort and precious time to beautifully style a form. django-crispy-forms solves this problem for us. It will let you control the rendering behavior of your Django forms in a very elegant and DRY way. Modules required:django : django installdjango-crispy
1 min read
Integrating Django with Reactjs using Django REST Framework
In this article, we will learn the process of communicating between the Django Backend and React js frontend using the Django REST Framework. For the sake of a better understanding of the concept, we will be building a Simple Task Manager and go through the primary concepts for this type of integration between React js and Django. Reactjs in a nuts
15+ min read