In this Python Django tutorial, I will show you the Django upload image file, where you will understand how to upload the image file on the Django server.
You will also understand the model field class ImageField that ensures only valid images should be uploaded to the Django server or it handles the image data.
Then you will build a Django project based on the course where the user can specify the author name, and course title and upload the images related to the courses. You will see how to upload the different formats of images.
Django Upload Image File
In today’s internet world, many websites use images such as online e-commerce that show product images that they sell. There is a website called Dribble where the artist shows their work through images and some blog websites with feature images.
So handling the upload of images is a very important feature of Web applications. In Django to handle the image data, there is a model field class called ImageField.
ImageField is a model field that exclusively accepts image formats for upload. Some image file formats are as follows:
- GIF (.gif)
- PNG (.png)
- TIFF (.tif, .tiff)
- Bitmap (.bmp)
- JPEG (.jpg, .jpeg)
- EPS (.eps)
- RAW Image Files (orf, .sr, .raw, .cr, .nef, and more)
Django Upload Image File Project Configuration
Create a Virtual Environment: Open the command prompt or terminal and create a virtual environment named ‘env’.
python -m venv env
Activate the environment.
env\Scripts\activate
Install the latest version of Django.
pip install django
Also, install the package pillow which is required for image processing.
pip install pillow
Create Project And App: First and foremost, we must develop a project and an app. So, to create it, use the given code below.
Create a Django project named ‘upload_image’ using the below command.
django-admin startproject upload_image
Change the directory to the upload_image.
cd upload_image
Then create a Django app ‘app_upload_image’ using the below command.
python manage.py startapp app_upload_image
Next, open the Django project in your preferred IDE such as Visual Studio Code.
Install App: After that, the project and app were successfully created. Now, you must install an application. Then include the Django app ‘app_upload_image’ under the INSTALLED_APPS section of the setting.py file.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app_upload_image',
]
Next, configure the setting.py file of your Django project ‘upload_image’ to specify the path where the uploaded image will be saved in your Django server or project.
To save uploaded files, modify settings: Now add the following lines to the end of the settings.py file.
import os
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
In the above code,
- First, import os.
- Then, specifying the URL to the media files, we use MEDIA_URL.
- After this, to specify the root path where the file will be saved, we use MEDIA_ROOT.
Media Folder: At your project level, make a new folder called ‘media’.
After the setup URLs at the project level for the urls.py file in the Django app ‘app_upload_file’
Project URLs: You must include a link to your newly developed app. Add the following code snippets in the urls.py file in your Django project ‘upload_image’.
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('app_upload_image.urls'))
]
App URLs: Also set up the URLs at the app level. So create a new file called urls.py in your Django app ‘app_upload_image’ and add the following lines of code.
from django.urls import path,include
from . import views
urlpatterns = [
path('uploadimage', views.UploadImage, name='UploadImage'),
]
Django Upload Image File Creating Model and Form
Let’s create a model named ‘Course’ or define a database schema for the table ‘Course’, after migration Django create a table in the database named ‘Course’. This table will store the course author, title and link to the uploaded image for the course.
Create Model: In models.py of your Django app ‘app_upload_file’, create a new Django Model “Course” by adding the following lines of code.
from django.db import models
class Course(models.Model):
author = models.CharField(max_length=100)
title = models.CharField(max_length=200)
image = models.ImageField(upload_to='images/')
In the above code,
- Here, we define the model fields author and title of type CharField, which stores the name of the author and the title of the course.
- To upload the images, the field image is defined as type ImageField.
- The upload_to option defines that the image will saved under the images/ directory within the media directory.
After creating the model, create a form that will rendered on the webpage for accepting the user input value.
Create Form: Create a new file called forms.py in your Django app ‘app_upload_image’. In that file add the following lines of code.
from django import forms
from .models import Course
class CourseForm(forms.ModelForm):
class Meta:
model = Course
fields = ['author', 'title', 'image']
If you want to know more about how to create a form in Django, then you can refer to the tutorial Create Model Form in Django
Django Upload Image File Creating View and Template
Next, create a view that decides what to show the user on the webpage and how to handle the coming request with data such as when the user submits the course form or uploads the image.
Create Views: Open the views.py file of your Django app ‘app_upload_image’ and add the following lines of code to handle the submitted data through the form.
from django.shortcuts import render, HttpResponse
from .forms import CourseForm
def UploadImage(request):
if request.method == 'POST':
form = CourseForm(request.POST,request.FILES)
if form.is_valid():
form.save()
return HttpResponse('The image saved successfully')
else:
form = CourseForm()
context = {
'form':form,
}
return render(request, 'upload.html', context)
- Here, we create the UploadImage view function which checks whether the request method is POST or not at line 5.
- After this, if the method is POST then we simply add a request.FILES along with the request.POST to the form to create an instance of form at line 6.
- Then, we use the is_valid() method on the form instance to check if the form contains correct data as defined in the CourseForm at line 7. If the form is valid, then form data is saved into the database and the image with the form is uploaded at line 8.
- Then at line 9, return to HttpResponse to the user with the message ‘The image saved successfully’ and from lines 10 to 15 render the HTML template with form if the request is not POST method or in case of any errors.
After creating views, create a template to show the Django form on the browser. For that create a new folder named templates in your Django app ‘app_upload_image’.
Create HTML Template: Now, in that folder create a upload.html template that shows the form by adding the following lines of code in the upload.html file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Upload Files</title>
</head>
<body>
<form method='post' enctype="multipart/form-data">
{% csrf_token %}
{{form.as_p}}
<input type="submit" value="Submit">
</form>
</body>
</html>
In the above code
- At line 12 create the <form> tag in the template file.
- Next, add the property enctype =”multipart/form-data” otherwise, the form won’t work.
- We also use the csrf_token tag in the form to avoid malicious attacks.
- Then, we use form.as_p tag to render Django forms as a paragraph.
Django Upload Image File Database Migration and Running Server
Now run the following commands one by one to create a table Course from the model that you have defined in the above section.
python manage.py migrate
python manage.py makemigrations
python manage.py migrate
In the above code,
- makemigrations: Makes migration files that have the model’s schema.
- migrate: Build tables according to the migration file’s schema.
Next, run the Django server by typing the below command in your terminal and uploading the image.
python manage.py runserver
Run Server: Start the server and access the form by writing the URL http://127.0.0.1:8000/uploadimage in your browser.
Now fill in the author and title, then choose any image from your local computer and click on the Submit button as shown in the below picture.
When we click on Submit button HTTP Response displays the message ‘The image saved successfully’.
To see the uploaded image, go to the directory media of your Django project and you see the image as shown in the below picture.
Let’s upload one more image in jpeg format as shown in the below picture.
To see the uploaded image which is in jpeg format, again open the media directory of your Django project as shown below.
Look at the above picture, you have uploaded the image in the jpeg format this time, you can upload different formats of images.
Conclusion
In this Python Django tutorial, you learned how to upload the image file in Django, you learned about the model field class ImageField that handles the image data. Then you built the Django project based on the course where you uploaded the different formats of images on the Django server.
You may like to read:
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.