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 Project

Django Project Let's start to use it. Each web app you want to build in Django is called a project; and a project is a collection of apps. A software is a series of...

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 and React

This article will discuss the overview of Django and React, their advantages, applications, and most importantly, how to implement react in Django. What is Django? Django is a free and open-source web...

6 minutes read.

Django Authentication

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 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 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 All Auth

For any web application, user registration and authentication are the essential parts. In Django, there are several applications like django-registration-redux to perform these tasks, but the major drawback is that...

6 minutes read.

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.

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

Creating View in Django

Creating View in Django    Django views are a key component of the frameworkbased applications.We are using Python function or class at their simplest, which takes up a web query and returns a web response.Views are used to get objects from the server, change objects if needed, render types, return HTML, and much more. Class Based View and Function based Django has two types of views: views based on functions (FBVs) and views based on class (CBVs).Initially, Django began with only FBVs, but then introduced CBVs as a way to model features so we didn't have to write boilerplate (i.e. the same software) code again and again.CBVs would be a way to increase efficiency, so you don't have to write as much code as you can. CBVs are classes of Python at their heart. Django ships with a range of "model" CBVs with pre-configured features that can be reused and often expanded.Then helpful names are given to these classes that explain what kind of functionality they provide.These are often referred to as "universal views" because they provide solutions to specific needs. The classes have a journal View function, or "view" for short, is simply a Python program that uses a web query and returns a web response. This response may include the HTML content of a web page, or a redirect, or a 404 error, or an XML file, or an image, etc. Example: You use a view to create a web page, remember that you need to connect a view to a URL to see it as a web page. Simple View We will create a simple view in myapplication to say “Welocome to django application” See the following view – from django.http import HttpResponse ...

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.

Django – Sending E-mails

Django – Sending E-mails Django comes with a light engine that is ready and simple to use to send emails. Similar to Python, you just need to import a smtplib. You just need to import django.core.mail in Django. Edit the project settings.py file to start sending emails and set  all the following options: EMAIL_HOST – server with smtp.EMAIL_HOST_USER – smtp server login key.EMAIL_HOST_PASSWORD ? Password credential for the smtp server.EMAIL_PORT – server port smtp.EMAIL_USE_TLS or _SSL – if it is secure connection then set True. Simple E-mail Sending To submit a simple e-mail, let's create it a "simpleEmail" view. from django.core.mail import...

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.

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.

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 ORM

Django is a Python web framework that enables easy and quick web development. Django has a handy and powerful feature called Django Object Relational Mapper, also known as Django ORM,...

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.

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.