How To Upload Images With Django

One of the most common requirement in any modern web application is the ability to take images or pictures from the users as input and save them on the server however Letting users upload files can have big security implications.

In this article, we will learn how to upload images in a Django application.

Uploading Images in Django

Django has two model fields that allow user uploads FileField and ImageField basically ImageField is a specialized version of  FileField that uses Pillow to confirm that a file is an image.

Let’s, start by creating models.

from django.db import models

class Image(models.Model):
    title = models.CharField(max_length=200)
    image = models.ImageField(upload_to='images')

    def __str__(self):
        return self.title

The image column is an ImageField field that works with the Django’s file storage API, which provides a way to store and retrieve files, as well as read and write them.

The upload_to parameters specify the location where images will be stored which for this model is MEDIA_ROOT/images/

Setting dynamic paths for the pictures is also possible.

image = models.ImageField(upload_to='users/%Y/%m/%d/', blank=True)

This will store the images in date archives like MEDIA_ROOT/users/2020/04/12

Now, Install Pillow by running the following command in your shell.

pip install Pillow

For Django to serve media files uploaded by users with the development server, add the following settings to the file of your project.

<span class="hljs-comment"># Base url to serve media files</span>
MEDIA_URL = <span class="hljs-string">'/media/'</span>

<span class="hljs-comment"># Path where media is stored</span>
MEDIA_ROOT = os.path.join(BASE_DIR, <span class="hljs-string">'media/'</span>)

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

Now add the following configuration in the project’s file.

<span class="hljs-keyword">from</span> django.conf <span class="hljs-keyword">import</span> settings
<span class="hljs-keyword">from</span> django.conf.urls.static <span class="hljs-keyword">import</span> static

urlpatterns = [
    path(<span class="hljs-string">'admin/'</span>,,
<span class="hljs-keyword">if</span> settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL,

With that Django’s development server is capable of serving media files. Next, we need to create a model form for the Image model.

from django import forms
from .models import Image

class ImageForm(forms.ModelForm):
    """Form for the image model"""
    class Meta:
        model = Image
        fields = ('title', 'image')

This will generate a form with fields title and image, which will be rendered in the templates. So let’s create a barebone template for file uploading.


<form method="post" enctype="multipart/form-data">
  {% csrf_token %}
   {{ form.as_p }}
  <button type="submit">Upload</button>

{% if img_obj %}
  <h3>Succesfully uploaded : {{img_obj.title}}</h3>
  <img src="{{ img_obj.image.url}}" alt="connect" style="max-height:300px">
{% endif %}

You must remember to include the enctype property in the form tag for the uploaded file to be attached to the request properly.

With that let’s write views for handling the form.

from django.shortcuts import render
from .forms import ImageForm

def image_upload_view(request):
    """Process images uploaded by users"""
    if request.method == 'POST':
        form = ImageForm(request.POST, request.FILES)
        if form.is_valid():
            # Get the current instance object to display in the template
            img_obj = form.instance
            return render(request, 'index.html', {'form': form, 'img_obj': img_obj})
        form = ImageForm()
    return render(request, 'index.html', {'form': form})

This is a very simple view since Django is doing all the work under the hood we are just validating the form and saving it on successful file upload. Now that we are done with the view let’s map it to a URL.

urlpatterns = [
    path('upload/', views.image_upload_view)

Save all the files and run the server and navigate to the URL you should see the form in action.

Uploading Images in Django


Support Django Central

If you appreciate my work, or if it has helped you along your journey. It would mean a lot to me if you could write a message on my wall and share a cup of coffee (or tea) with me.
Buy Me a Coffee at

19 thoughts on “How To Upload Images With Django”

  1. Thanks for a very crisp and readable article. Is there a functional source zip available? I saved the files as described above and ran the server but faced a challenge:

    – index.html appears to be incomplete. Title input and file selection interface are missing.

    Couldn’t continue further.

    • He has shown that option. As you can see after saving the form he is storing the form instance to a variable and passing to context to fetch the image in template.

  2. I’m having issues with where to create the index.html and And which urls file needs to be updated. Could anyone please clarify?

  3. i followed the tutorial but am getting a 404 page when going to

    Using the URLconf defined in project.urls, Django tried these URL patterns, in this order:

    / [name=’post_detail’]
    The current path, upload/, matched the last one.

    not sure what i did wrong, and would appreciate help thanks!

  4. Hi,
    How to store image to a MySQL database dynamically? I mean when we create a registration form there we have to capture the image of each member,then this image should be stored in the database.How is this possible??


Leave a Comment