Django Views are one of the vital participants of the MVT Structure of Django. As per Django Documentation, A view function is a Python function that takes a Web request and returns a Web response. This response can be the HTML contents of a Web page, a redirect, a 404 error, an XML document, an image, or anything that a web browser can display.
Django Views
Django views are part of the user interface — they usually render the HTML/CSS/Javascript in your Template files into what you see in your browser when you render a web page. (Note that if you've used other frameworks based on the MVC (Model-View-Controller), do not get confused between Django views and views in the MVC paradigm. Django views roughly correspond to controllers in MVC, and Django templates to views in MVC.)

Illustration of How to create and use a Django view using an Example. Consider a project named geeksforgeeks having an app named geeks.
Refer to the following articles to check how to create a project and an app in Django.
After you have a project ready, we can create a view in geeks/views.py,
Python3
# import Http Response from django
from django.http import HttpResponse
# get datetime
import datetime
# create a function
def geeks_view(request):
# fetch date and time
now = datetime.datetime.now()
# convert to string
html = "Time is {}".format(now)
# return response
return HttpResponse(html)
Let’s step through this code one line at a time:
- First, we import the class HttpResponse from the django.http module, along with Python’s datetime library.
- Next, we define a function called geeks_view. This is the view function. Each view function takes an HttpRequest object as its first parameter, which is typically named request.
- The view returns an HttpResponse object that contains the generated response. Each view function is responsible for returning an HttpResponse object.
For more info on HttpRequest and HttpResponse visit - Django Request and Response cycle – HttpRequest and HttpResponse Objects
Let's get this view to working, in geeks/urls.py,
Python3
from django.urls import path
# importing views from views..py
from .views import geeks_view
urlpatterns = [
path('', geeks_view),
]
Now, visit http://127.0.0.1:8000/.

To check how to make a basic project using MVT (Model, View, Template) structure of Django, visit Creating a Project Django.
Django views are divided into two major categories:
- Function Based Django Views
- Class Based Django Views

Function Based Views in Django
Function based views are written using a function in python which receives as an argument HttpRequest object and returns an HttpResponse Object. Function based views are generally divided into 4 basic strategies, i.e., CRUD (Create, Retrieve, Update, Delete). CRUD is the base of any framework one is using for development.
How to use Function based view in Django?
Let's Create a function-based view list view to display instances of a model. Let's create a model of which we will be creating instances through our view. In geeks/models.py,
Python3
# import the standard Django Model
# from built-in library
from django.db import models
# declare a new model with a name "GeeksModel"
class GeeksModel(models.Model):
# fields of the model
title = models.CharField(max_length = 200)
description = models.TextField()
# renames the instances of the model
# with their title name
def __str__(self):
return self.title
After creating this model, we need to run two commands in order to create Database for the same.
Python manage.py makemigrations
Python manage.py migrate
Now let's create some instances of this model using shell, run form bash,
Python manage.py shell
Enter following commands
>>> from geeks.models import GeeksModel
>>> GeeksModel.objects.create(
title="title1",
description="description1").save()
>>> GeeksModel.objects.create(
title="title2",
description="description2").save()
>>> GeeksModel.objects.create(
title="title2",
description="description2").save()
Now if you want to see your model and its data in the admin panel, then you need to register your model.
Let's register this model. In geeks/admin.py,
Python3
from django.contrib import admin
from .models import GeeksModel
# Register your models here.
admin.site.register(GeeksModel)
Now we have everything ready for the back end. Verify that instances have been created from http://localhost:8000/admin/geeks/geeksmodel/

Let's create a view and template for the same. In geeks/views.py,
Python3
from django.shortcuts import render
# relative import of forms
from .models import GeeksModel
def list_view(request):
# dictionary for initial data with
# field names as keys
context ={}
# add the dictionary during initialization
context["dataset"] = GeeksModel.objects.all()
return render(request, "list_view.html", context)
Create a template in templates/list_view.html,
html
<div class="main">
{% for data in dataset %}.
{{ data.title }}<br/>
{{ data.description }}<br/>
<hr/>
{% endfor %}
</div>
Let's check what is there on http://localhost:8000/

Similarly, function based views can be implemented with logics for create, update, retrieve and delete views.
Django CRUD (Create, Retrieve, Update, Delete) Function Based Views :-
Class Based Views in Django
Class-based views provide an alternative way to implement views as Python objects instead of functions. They do not replace function-based views, but have certain differences and advantages when compared to function-based views:
- Organization of code related to specific HTTP methods (GET, POST, etc.) can be addressed by separate methods instead of conditional branching.
- Object oriented techniques such as mixins (multiple inheritance) can be used to factor code into reusable components.
Class-based views are simpler and efficient to manage than function-based views. A function-based view with tons of lines of code can be converted into class-based views with few lines only. This is where Object-Oriented Programming comes into impact.
How to use Class based view in Django?
In geeks/views.py,
Python3
from django.views.generic.list import ListView
from .models import GeeksModel
class GeeksList(ListView):
# specify the model for list view
model = GeeksModel
Now create a URL path to map the view. In geeks/urls.py,
Python3
from django.urls import path
# importing views from views..py
from .views import GeeksList
urlpatterns = [
path('', GeeksList.as_view()),
]
Create a template in templates/geeks/geeksmodel_list.html,
html
<ul>
<!-- Iterate over object_list -->
{% for object in object_list %}
<!-- Display Objects -->
<li>{{ object.title }}</li>
<li>{{ object.description }}</li>
<hr/>
<!-- If objet_list is empty -->
{% empty %}
<li>No objects yet.</li>
{% endfor %}
</ul>
Let's check what is there on http://localhost:8000/

Django CRUD (Create, Retrieve, Update, Delete) Class Based Generic Views :-
Similar Reads
Django Tutorial | Learn Django Framework
Django, built with Python, is designed to help developers build secure, scalable, and feature-rich web applications quickly and efficiently. Whether you're a beginner looking to create your first dynamic website or an experienced developer aiming to enhance your skills, this tutorial will guide you
11 min read
Django view
Views In Django | Python
Django Views are one of the vital participants of the MVT Structure of Django. As per Django Documentation, A view function is a Python function that takes a Web request and returns a Web response. This response can be the HTML contents of a Web page, a redirect, a 404 error, an XML document, an ima
6 min read
Django Function Based Views
Django is a Python-based web framework which allows you to quickly create web application without all of the installation or dependency problems that you normally will find with other frameworks. Django is based on MVT (Model View Template) architecture and revolves around CRUD (Create, Retrieve, Up
7 min read
Django Class Based Views
Class-Based Views (CBVs) allow developers to handle HTTP requests in a structured and reusable way. With CBVs, different HTTP methods (like GET, POST) are handled as separate methods in a class, which helps with code organization and reusability.Advantages of CBVsSeparation of Logic: CBVs separate d
6 min read
Class Based vs Function Based Views - Which One is Better to Use in Django?
Django, a powerful Python web framework, has become one of the most popular choices for web development due to its simplicity, scalability and versatility. One of the key features of Django is its ability to handle views and these views can be implemented using either Class-Based Views (CBVs) or Fun
6 min read
Django Templates
Templates are the third and most important part of Django's MVT Structure. A Django template is basically an HTML file that can also include CSS and JavaScript. The Django framework uses these templates to dynamically generate web pages that users interact with. Since Django primarily handles the ba
7 min read
Django Static File
Static Files such as Images, CSS, or JS files are often loaded via a different app in production websites to avoid loading multiple stuff from the same server. This article revolves around, how you can set up the static app in Django and server Static Files from the same.Create and Activate the Virt
3 min read
Django Model
Django Models
A Django model is the built-in feature that Django uses to create tables, their fields, and various constraints. In short, Django Models is the SQL Database one uses with Django. SQL (Structured Query Language) is complex and involves a lot of different queries for creating, deleting, updating, or a
10 min read
Django model data types and fields list
Django models represent the structure of your database tables, and fields are the core components of those models. Fields define the type of data each database column can hold and how it should behave. This artcle covers all major Django model field types and their usage.Defining Fields in a ModelEa
4 min read
Built-in Field Validations - Django Models
Built-in Field Validations in Django models are the default validations that come predefined to all Django fields. Every field comes in with built-in validations from Django validators. For example, IntegerField comes with built-in validation that it can only store integer values and that too in a p
3 min read
How to use User model in Django?
The Djangoâs built-in authentication system is great. For the most part we can use it out-of-the-box, saving a lot of development and testing effort. It fits most of the use cases and is very safe. But sometimes we need to do some fine adjustment so to fit our Web application. Commonly we want to st
3 min read
Meta Class in Models - Django
Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. Itâs free and open source. D
3 min read
get_object_or_404 method in Django Models
Some functions are hard as well as boring to code each and every time. But Django users don't have to worry about that because Django has some awesome built-in functions to make our work easy and enjoyable. Let's discuss get_object_or_404() here. What is get_object_or_404 in Django?get_object_or_404
2 min read
Django Admin Interface - Python
Prerequisites: Django Introduction and Installation Creating a ProjectThe Django Admin Interface is one of the most powerful features of the Django framework. It provides a ready-to-use interface for managing project data through models, allowing developers and site administrators to perform Create,
3 min read
More topics on Django
Handling Ajax request in Django
AJAX (Asynchronous JavaScript and XML) is a web development technique that allows a web page to communicate with the server without reloading the entire page. In Django, AJAX is commonly used to enhance user experience by sending and receiving data in the background using JavaScript (or libraries li
3 min read
Python | User groups with Custom permissions in Django
Let's consider a trip booking service, how they work with different plans and packages. There is a list of product which subscriber gets on subscribing to different packages, provided by the company. Generally, the idea they follow is the level-wise distribution of different products. Let's see the
4 min read
Django Admin Interface - Python
Prerequisites: Django Introduction and Installation Creating a ProjectThe Django Admin Interface is one of the most powerful features of the Django framework. It provides a ready-to-use interface for managing project data through models, allowing developers and site administrators to perform Create,
3 min read
Python | Extending and customizing django-allauth
Prerequisite: Django-allauth setup and Configuration Let's deal with customizing django-allauth signup forms, and intervening in registration flow to add custom processes and validations. Extending the Signup Form or adding custom fields in Django-allauth: One of the most common queries about allaut
4 min read
Django - Dealing with Unapplied Migration Warnings
Django is a powerful web framework that provides a clean, reusable architecture to build robust applications quickly. It embraces the DRY (Don't Repeat Yourself) principle, allowing developers to write minimal, efficient code.Create and setup a Django project:Prerequisite: Django - Creating projectA
2 min read
Sessions framework using django - Python
Django sessions let us store data for each user across different pages, even if theyâre not logged in. The data is saved on the server and a small cookie (sessionid) is used to keep track of the user.A session stores information about a site visitor for the duration of their visit (and optionally be
3 min read
Django Sign Up and login with confirmation Email | Python
Django provides a built-in authentication system that handles users, login, logout, and registration. In this article, we will implement a user registration and login system with email confirmation using Django and django-crispy-forms for elegant form rendering.Install crispy forms using the termina
7 min read