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.captionUpload_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
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/')
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)
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
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__'
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 %}
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})
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")
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.




