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

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 CSRF

Django is a high-level python based web framework. Django is open source and free to use for all. Django provides many features to web developers like scalability, security, rapid development,...

4 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.

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 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 App

Django is a Python-based web framework that is based on the Model View Template architecture. In this post, we will go through the installation and setup for our first Django...

4 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 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.

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.

Django Filters

Django is a high-level python based web framework. Django is mostly used as a backend engine for websites. Nowadays, every website communicates to a database to fetch all the information...

3 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.

Django CMS vs WordPress

Both Django CMS and WordPress belong "Self-Hosted Blogging" or "Content Management System (CMS)" category, that is used to manage digital content. Bloggers usually use these platforms. Django CMS Django is one of...

4 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 vs Laravel

Django Overview Django is a Python Programming Open Source framework for web development. It was released in 2008 and was developed by two web developers named Adrian Holovaty and Simon Willison....

4 minutes read.

Django Pagination

Django is an open-source free to use python based web framework. Django provides many inbuilt tools for web developers to provide rapid web development. One of these tools is pagination....

4 minutes read.

Django Template System

Django Template System Django allows Python and HTML to be divided, the Python goes into views, and HTML goes into templates. Django relies on the render feature and the language of the Django Model...

5 minutes read.

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,...

3 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.

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