How to Image Upload in Python Django ?

Published On: 28/06/2022 | Category: Django Python

Hi Dev,

I am going to explain you example of how to image upload in python django. This tutorial will give you simple example of how to upload image in python django. this example will help you how to upload image in django form. you can understand a concept of django image upload example. you will do the following things for how to image upload in python django blog.

Here i will give you we will help you to give example of how to upload image in django. So let's see the bellow example:

Step 1 : Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject example
Step 2 : Create a App
python3 startapp image

Next, you need to add it in the file as follows:

Step 3 : Database Setup

Next step, we will modify the file and update the database settings to configure the mydb database:
    'default': {  
        'ENGINE': 'django.db.backends.mysql',  
        'NAME': 'example',  
Step 4 : Update File

Next step, we will modify the file and add the below code:

  • MEDIA_ROOT: is for server path to store files in the computer.
  • MEDIA_URL:is the reference URL for browser to access the files over Http.
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
And in the we should edit the configuration like this example/
from django.conf import settings
from django.conf.urls.static import static
if settings.DEBUG:
        urlpatterns += static(settings.MEDIA_URL,
Step 5 : Create a Model

In this step we will require the database model for storing contacts.Open the image/ file and add the following code:

from django.db import models

# Create your models here.

class UserImage(models.Model):
    name = models.CharField(max_length=50)
    image = models.ImageField(upload_to='images/')

After creating these model, you need to create migrations using the following command:

Step 5 : Create a Migrations
python makemigrations

After successfully run the above command go to the image/migrations/

# Generated by Django 4.0.5 on 2022-06-27 09:36

from django.db import migrations, models

class Migration(migrations.Migration):

    initial = True

    dependencies = [

    operations = [
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=50)),
                ('image', models.ImageField(upload_to='images/')),

Next, you need to migrate your database using the following command:

python migrate
Step 5 : Create a Form

In this step we will require here we are dealing with model form to make content easier to understand. and add the following code:

from django import forms
from .models import *

class UserForm(forms.ModelForm):

    class Meta:
        model = UserImage
        fields = ['name', 'image']
Step 6 : Creating the Views

In this step, we need to create the views for performing fetch record to the database.Open the image/ file and add:

from django.http import HttpResponse
from django.shortcuts import render, redirect
from .forms import *
from django.contrib import messages

# Create your views here.
def userProfile(request):

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

        if form.is_valid():
            messages.success(request, 'Image Upload Successfully')
        form = UserForm()
    return render(request, 'profileImg.html', {'form' : form})
Step 7 : Creating Django Templates

In this step i will use bootstrap 4 crispy forms if you don't know about that so i will already post article first you can read this Bootstrap 4 Crispy Forms

Next, open the image/templates/profileImg.html file and the add:

{% load crispy_forms_tags %}
<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <title>Profile Image</title>
    <link rel="stylesheet" href="[email protected]/dist/css/bootstrap.min.css">
    <script src="[email protected]/dist/jquery.slim.min.js"></script>
    <script src="[email protected]/dist/umd/popper.min.js"></script>
    <script src="[email protected]/dist/js/bootstrap.bundle.min.js"></script>
    <div class="container mt-5 pt-5">
        <div class="row d-flex justify-content-center">
            <div class="col-md-8">
                {% if messages %}
                    <div class="alert alert-success alert-dismissible">
                        <button type="button" class="close" data-dismiss="alert">×</button>
                        {% for message in messages %}
                            {{ message }}
                        {% endfor %}
                {% endif %}
                <div class="card">
                    <div class="card-header bg-secondary text-white">
                        <h3>How to image Upload in Python Django ? -</h3>
                    <div class="card-body">
                        <form method = "post" enctype="multipart/form-data">
                            {% csrf_token %}
                            {{ form|crispy }}
                            <div class="row">
                                <div class="col-md-12 text-center">
                                    <button type="submit" class="btn btn-success">Upload</button>
Step 8 : Creating Urls

In this section, we’ll create the urls to access our views.Go to the example/ file and update it as follows:

from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from image.views import *

urlpatterns = [
    path('image-upload', userProfile, name = 'image_upload'),

if settings.DEBUG:
        urlpatterns += static(settings.MEDIA_URL,
Step 9 : Run the Server

In this step, we’ll run the local development server for playing with our app without deploying it to the web.

python runserver

Next, go to the http://localhost:8000/ address with a web browser.

I Hope It will help you....