Django Image Upload

Django is a python based web framework that uses Model View Template as its architecture. Django provides really quick web development with its functionalities. While we are building a website, many times, we will require to add some images or add an upload file widget to our website. Uploading an Image is one of the most common requirements of a website, and after uploading, we also need to store it on the server or the database.

Django provides two model fields to file upload, which is FileFieldand ImageField. ImageField is a specific case of FileField in which a file can only be in jpg/jpeg/png format. ImageField uses Pillow to validate if the file uploaded is an Image or not.

Let us create a model to upload the image.

Models.py

fromDjango.db import models


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


def __str__(self):
returnself.title

In this, we have created an image variable which is of type ImageField. ImageField will provide a way to read and write images. The argument upload_to decides where the uploaded image will be stored. Here we have specified the path  MEDIA_ROOT/images. 

The next step is to specify MEDIA_ROOT in settings.py file. Add the following code in settings.py file:

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

MEDIA_URL is the reference URL for the browser.

Now we also have to add some code in the urls.py file:

fromDjango.conf import settings
fromDjango.conf.urls.static import static


urlpatterns = [
path('admin/', admin.site.urls),
    ...]
ifsettings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)

This will enable the server to serve the media files.

Now we need to create a forms.py file.

fromDjango import forms

fromDjango import forms
from .models import Image




classImageForm(forms.ModelForm):
class Meta:
model = Image
fields = ('title', 'image')

We have ModelForms to create the forms. The advantage of using the model forms is that we don't need to code the validation for the form input explicitly. Django will take care of it. This form will create title and image fields. Now we need to create a view.py file to render the form.

Index.html

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


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

In the above file, we are making a POST request to send the data. To send the image we also, have to specify the encoding type to multipart/formdata, which will ensure the entire file gets sent as data.

Views.py filehandle the form. It takes the request from the user and renders an html page.

Views.py

from Django.shortcuts import render, redirect
from .forms import *
  
defimage_view(request):
  
    if request.method == 'POST':
        form = ImageForm(request.POST, request.FILES)
  
        if form.is_valid():
            form.save()
            return redirect('success')
    else:
        form = ImageForm()
    return render(request, 'index.html', {'form' : form})

In this view, we are just validating the file uploaded and then rendering some html pages according to it. Whenever this view is called and the request is POST, it will create the ImageForm to get the image and then shows the success message. After creating the view, all we need to do is map the URL to it.

 Add the following code to your URL patterns list:

Urls.py:

urlpatterns = [
    ......
path('image/', views.image_view)
    ......
]

We are done with the coding part. Now just save the files and run the server by the following command:

Python manage.py runserver

Go to the browser and navigate to the specified URL. You should see an image form.

Django Image Upload

Related Topics

How to create an app in Django

Create an application in Django Django is famous for its unique and fully managed application structure. For each functionality, an application can be created as a completely independent module. This article will take...

2 minutes read.

Best Django courses

In this tutorial, we will see various courses in python Django available on the internet. Django has become popular these days, so courses on it are also increasing day by...

7 minutes read.

Django Framework

Django is a popular high-level open-source web development Python framework based on follows Model View Template (MVT) architecture that allows rapid development. It. It provides common functionality like Admin Interface,...

3 minutes read.

Django CMS

Django is one of the most popular open-source Python web development framework. Developers use Django to build a website from scratch. Like WordPress, Django CMS is also a Content Management...

9 minutes read.

Django Environment Setup

Django is a free and open-source web framework, which uses Python as its programming language. It is based on Model View Template (MVT) architecture. A framework is a collection of...

4 minutes read.

How to Implement Multiple User Types with Django

Django Framework: Django is a framework that can make web applications more accessible and faster. Django is an open-source collection of python libraries, and Django can be used for both the...

3 minutes read.

Life Cycle of Django

Life Cycle of Django Request - Response life cycle in Django  Thebasic principle of http protocol is the client sends a request to the server based on the request data, and the server sends...

3 minutes read.

Django Stack

Django is a popular Python web application framework that adheres to the "batteries-included" tenet. Batteries-guiding included idea is that common functionality for creating web applications should be provided with the...

5 minutes read.

Django Create Superuser

For managing the website, we need an Admin while creating the Django application. In order to create the admin user, create superuser command is used. The superuser is called the...

3 minutes read.

How to connect Django with Mysql

Any web application contains some data that comes from the input of the end-users. Thus, the database is required to handle those data. Several databases could be used to connect...

3 minutes read.

Django Messages

Django Framework Django is a framework that can make web applications more accessible and faster. Django is an open-source collection of python libraries, and Django can be used for both the...

6 minutes read.

Django Installation

Django Installation Django development environment consists of installing and setting up Python, Django, and a Database System since Django deals with a web application. Below the statement will guide you through installing Python 3.8.0 and...

2 minutes read.

Django Class Based Views

Class-based views were developed to solve the problem of customizing function-based generic views. We can arrange our view code Object-Oriented by using class views. Class-based views do more than function-based...

3 minutes read.

Django Create Project

Django is an open-source free to use web framework which is based on Python. Django uses Model-View-Template as its architecture. The final version of Django was released in 2008. Django...

4 minutes read.

Django Admin

To manage the content of the website, e.g., adding and deleting posts, web developers need an admin portal on the website. The admin portal allows trusted users, also knows as...

3 minutes read.

Features of Django

Features of Django Offers High Security:- Django is super secure. To prove the feature, we can always take examples of lots of websites which are present worldwide and possess huge traffic. Django is secure because it covers the...

3 minutes read.

Uses of Django

Django is a free and open-source Python-based web framework, which offers great functionalities to its users. Django was developed in 2003, and the final version was released in 2008 by...

3 minutes read.

Django Frontend

Django Django is a framework that can make web applications more accessible and faster. Django is an open-source collection of python libraries, and Django can be used for both the front...

3 minutes read.

Django REST Framework

Django REST Framework (DRF)is an open-source, powerful, and flexible toolkit used to build RESTful web APIs. It is built upon the Django framework. DRF increases the development speed. Django and...

4 minutes read.

Django MVT

 MVT(Model View Template) MVT means Model View Template is a software design pattern The View is used to implement the business logic and to communicate with a model for data transmission and to...

2 minutes read.