Support Our Site

To ensure we can continue delivering content and maintaining a free platform for all users, we kindly request that you disable your adblocker. Your contribution greatly supports our site's growth and development.

How To Upload Images With Django

3 min read

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.

Django, a powerful and popular web framework for Python, provides an easy and effective way to handle file uploads, including image uploads

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.

models.py

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 settings.py file of your project.

settings.py

# Base url to serve media files
MEDIA_URL = '/media/'
# Path where media is stored
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')

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 urls.py file.

urls.py

from django.conf import settings
from django.conf.urls.static import staticurl
patterns = [    
path('admin/', admin.site.urls),
    ...]
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL,
                          document_root=settings.MEDIA_ROOT)

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

forms.py

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.

index.html

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

views.py

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():
            form.save()
            # 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})
    else:
        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.

urls.py

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

 Congratulations! You have successfully implemented image uploads in your Django project. Feel free to further customize the design and functionality to suit your specific needs.


DJANGO

Latest Articles

Latest from djangocentral

How to Use Subquery() in Django With Practical Examples

In the realm of web development, Django stands as a powerful and versatile framework for building robust applications. One of the key aspects of developing efficient and optimized web applications is handling database queries effectively. In this article…
Read more →

4 min read

DRF Serializer: Handling OrderedDict and Converting It to a Dictionary or JSON

In Django Rest Framework (DRF) tests, when you access serializer.data, you might encounter an OrderedDict instead of a regular dictionary. This behavior is intentional and reflects the design of DRF's serialization process.Understanding the Problem The u…
Read more →

3 min read

Django Rest Framework CheetSheet: Mastering API Development

Django Rest Framework (DRF) is a powerful toolkit that makes building robust and scalable web APIs with Django a breeze. Whether you're a seasoned Django developer or a newcomer, having a comprehensive cheat sheet at your disposal can be a game-changer. …
Read more →

5 min read

How to Perform NOT Queries in Django ORM

In Django, performing NOT queries allows you to exclude certain records from the query results based on specific conditions. The NOT operator, represented by the tilde (~) when used in conjunction with the Django ORM's Q object, helps you construct compl…
Read more →

3 min read