Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


How to upload images in Django



Django is a web framework powered by python and is widely known as the web framework for perfectionists. It enables you to get your web applications up and running with minimal codes.

It is structured in the MVTModel View Template framework pattern and handles some operations, like uploading files and images, in unique ways.

What to know before uploading your image

  • request.FILES holds data about files submitted to the server.

  • The form used to submit the file must have the enctype="multipart/form-data" attribute included.

  • The form should have a method value of POST and should have the {% csrf_token %} included as well. The input for the image submission must have the input type attribute value of the file.

  • The Django model ImageField creates a column that holds a string value. This string is the URL to the image location on the file system.

  • Images uploaded are not saved to the database. Instead, they’re saved to the folder you indicate when creating your image model. Save this folder in the media_url location you indicate in the file.

That is the basics of image/file upload in Django. Let’s now see the steps to upload an image.

Steps to upload images in Django

The following steps outline a simple image file upload in Django.

These steps assume you clearly understand the basic structure of a Django project.

Step 1

Add the following code to the end of your file.

MEDIA_URL = '/media/'

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

MEDIA_ROOT indicates the root folder the server uses for media storage. MEDIA_URL is the reference URL the browser uses to access the file over HTTP.

Step 2

Create a file in your app folder and not the project folder if you don’t already have one. Then add the following code to it.

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)

In this file, there is a check for the DEBUG mode.This can be found in file.

With DEBUG status set as true, the if statement is executed serving the files with django.contrib.staticfiles.views.serve() in development server. It makes serving these files in the local server easier.

Step 3

Create your model class in the file. It may be as simple as the example below or significantly more complex.

from django.db import models

class Student(models.Model):
    name = models.CharField(max_length=50)
    avatar = models.ImageField(upload_to='uploads/')

def __str__(self):
     return self.title

In the code above, the models.ImageField indicates the folder that holds the image and creates a row on the database table that contains the URL that points to the image.

Step 4

Using Django’s model form, create a form class for handling our example student form and link it with the model in the file.

from django import forms
from .models import *
class StudentForm(forms.ModelForm):
    class Meta:
        model = Student
        fields = ['name', 'avatar']

With the help of this form, Django will present two fields to the user through the HTML form: one for name input, which will be text type, and one for image upload input.

Step 5

Next, create the HTML form that displays the input fields as indicated in the file.


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

The form input displays as a paragraph because of the form.as_p python command.

Step 6

Next, create your view function in to handle the upload of the form and its data.

from django.http import HttpResponse
from django.shortcuts import render, redirect
from .forms import *
/*#Create your views here.*/
def avatarView(request):
    if request.method == 'POST':
        form = StudentForm(request.POST, request.FILES)
        if form.is_valid():
            return redirect('success')
        form = StudentForm()
    return render(request, 'studentform.html', {'form' : form})
def uploadok(request):
    return HttpResponse(' upload successful')

When a form is submitted, the avatarView function checks if there is a POST request. If there is, the StudentForm class in is called to handle the form, while image data goes into the request.FILES list object. The validity of the form is also checked. If valid, the form and its input is saved and the user is redirected to a submit successful page. If it is not valid, the form is displayed again.

The success view function will display a submit successful message.

Step 7

Lastly, update the file we created earlier in our app folder as follows.

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 *
urlpatterns = [
    path('image_upload/', avatarView, name = 'image_upload'),
    path('success/', uploadok, name = 'success'),
if settings.DEBUG:
        urlpatterns += static(settings.MEDIA_URL,

You’re done setting up, now run migration to create your model and run your server. With the server up and running, go to your browser and run your application. You should see something that looks like so:



View all Courses

Keep Exploring