Table of contents
1.
Introduction
2.
Uploading images in Django
2.1.
model.py
2.2.
Upload_to
2.3.
settings.py
2.4.
urls.py
2.5.
forms.py
2.6.
templates/image_forms.html
2.7.
view.py
2.8.
sampleapp/urls.py
3.
Frequently Asked Questions
4.
Key Takeaway
Last Updated: Mar 27, 2024

Uploading Images in Django

Author Aditya Kumar
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

One of the essential elements of any modern web application is uploading images and here we will learn about uploading images in Django. It enables the user to upload an image or photograph to the server. We can utilise this to make a lovely online application that allows people to upload photographs with captions.

 

Uploading images in Django

Most web applications deal with files or photos, and Django has two model fields that allow users in uploading files and uploading images in Django. FileField and ImageField are the fields in question; ImageField is a modified version of FileField that utilizes Pillow to verify that the file is an image. Let's have a look at an example of model creation.

model.py

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

    def __str__(self):
        return self.caption
You can also try this code with Online Python Compiler
Run Code

Upload_to

specifies where the images should be stored; by default, Django generates a directory under the media directory, which is created automatically when we upload a photo. There is no need to create a media directory explicitly.

The UploadImage model comprises two fields: a caption and a picture. Django's file storage API will be implemented in the picture field. This API allows you to read and write files and save and retrieve them. The upload to argument indicates where the image will be kept in a file.

We don't have to manually build the media directory; it will be created when we upload a picture.

First and first, we must install the pillow library, which aids in picture manipulation. The following pip command can be used to install it.

pip install Pillow
You can also try this code with Online Python Compiler
Run Code

 

Now add the following settings to your project's settings.py file.

settings.py

# The reference URL for the browser to access the files over HTTP is MEDIA URL.
MEDIA_URL = '/media/'

#Media is stored in this path.
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
You can also try this code with Online Python Compiler
Run Code

 

The following configuration should be added to the urls.py file in the next stage.

urls.py

from django.contrib import admin  
from django.urls import path  
from django.urls.conf import include  
from django.conf import settings  
from django.conf.urls.static import static  
  
urlpatterns = [  
    path('admin/', admin.site.urls),  
    path('', include(('sampleapp.urls'), namespace='sampleapp'))  
      
]  
if settings.DEBUG:  
        urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) 
You can also try this code with Online Python Compiler
Run Code

 

We've completed all of the necessary setups and are now ready to perform the commands below.

python manage.py makemigations
python manage.py migrate
You can also try this code with Online Python Compiler
Run Code

 

After running this script, we're ready to develop a form that will accept the user's image as input. Let's start by making a form.

forms.py

from django.db import models  
from django.forms import fields  
from .models import UploadImage  
from django import forms  
  
  
class UserImage(forms.ModelForm):  
    class meta:  
        # To specify the model to be used to create form  
        models = UploadImage  
        # It includes all the fields of model  
        fields = '__all__' 
You can also try this code with Online Python Compiler
Run Code

 

The benefit of using a Django model form is that it can handle form validation without requiring explicit declaration in the script. It will also populate the form fields on the website with the model fields from the model.py file.

To see this form, go to the template folder and create the image_form.html file.

templates/image_forms.html

{% extends 'base.html' %}

{% block content %}
<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.caption}}</h3>
<img src="{{ img_obj.image.url}}" alt="connect" style="max-height:300px">
{% endif %}

{% endblock content %}
You can also try this code with Online Python Compiler
Run Code

 

The enctype = "multipart/form-data" specifies that files transmitted via POST. The user cannot deliver the file through a POST request without enctype. To work with the files or images, it is essential to include them in the form.

The csrf_token is used to prevent Cross-Site Request Forgery.

All of the components are in form.as_p is wrapped in HTML paragraph tags. The benefit is that you won't have to build a loop in the template to add HTML to each title and field.

We'll now create the view that will handle the requests.

view.py

from django.shortcuts import redirect, render  
from sampleapp.forms import UserImageForm  
from .models import UploadImage  
  
def image_request(request):  
    if request.method == 'POST':  
        form = UserImageForm(request.POST, request.FILES)  
        if form.is_valid():  
            form.save()  
  
            # Getting the current instance object to display in the template  
            img_object = form.instance  
              
            return render(request, 'image_form.html', {'form': form, 'img_obj': img_object})  
    else:  
        form = UserImageForm()  
  
    return render(request, 'image_form.html', {'form': form}) 
You can also try this code with Online Python Compiler
Run Code

 

The above view is straightforward, and it handles photos similarly to a standard form. The post request will be generated when we upload the image. The form is confirmed and saved in the media folder automatically. One thing to keep in mind is that we utilize form.instance to acquire the image object, which will be used to display the image on the web page.

Let's make a URL for this page.

sampleapp/urls.py

from django.URLs import path  
from .views import image_request  
  
app_name = 'sampleapp'  
urlpatterns = [  
    path('', image_request, name = "image-request")  
You can also try this code with Online Python Compiler
Run Code

 

After executing the localhost server, we obtain the following form.

This file will be saved to the media/images folder that we specified in the model box.

Frequently Asked Questions

1. In Django, what are views?

A view function, also known as a "view," is a Python function that receives a web request and provides a web response. This answer could be the HTML content of a web page, a redirect, a 404 error, an XML document, or a picture, among other things.

Example:

from django.http import HttpResponse
def sample_function(request):
 return HttpResponse(“Welcome to Django”)
You can also try this code with Online Python Compiler
Run Code

There are two kinds of views:

  • Function-Based Views: In this case, we import our view as a function.
  • Class-Based Views: It's a method based on objects.

 

2. What are Django URLs, and how do I use them?

URLs are one of the most crucial components of a web application, and Django's URLconf module gives you an intuitive way to create your custom URLs (URL Configuration). This Python module's fundamental feature lets you create your URLs in Django and then map them to the python function (View function). These URLs can be either static or dynamic. These URLs are found in urls.py, where they are matched with the view function that corresponds to them.

Basic Syntax:

from django.urls import path
from . import views
urlpatterns = [
   path('data/2020/', views.data_2020),
   path('data/<int:year>/', views.data_year)
]
You can also try this code with Online Python Compiler
Run Code

Key Takeaway

We learned about uploading Images in Django in this article. Django provides a straightforward interface for uploading images or files. All we have to do now is configure the model form's field and define an ImageField. By using the same technique, we may upload any file (.xml,.pdf,.word,.etc), but we'll need to convert ImageField to FileField in the model's field.

You may also want to explore more articles on Django then you can visit our archives on Django where you can find more relevant topics related to Django such as top interview questions in Django or beginning with Django.

Live masterclass