Django Function Based Views
Last Updated :
23 Sep, 2024
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, Update, Delete) operations. CRUD can be best explained as an approach to building a Django web application. In general CRUD means performing Create, Retrieve, Update and Delete operations on a table in a database. Let's discuss what actually CRUD means,

Create - create or add new entries in a table in the database.Â
Retrieve - read, retrieve, search, or view existing entries as a list(List View) or retrieve a particular entry in detail (Detail View)
Update - update or edit existing entries in a table in the databaseÂ
Delete - delete, deactivate, or remove existing entries in a table in the database
Django Function Based Views - CRUD Operations
Illustration of How to create and use CRUD 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 and an app, 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 we will create a Django ModelForm for this model. Refer this article for more on modelform - Django ModelForm – Create form from Models. create a file forms.py in geeks folder,Â
Python
from django import forms
from .models import GeeksModel
# creating a form
class GeeksForm(forms.ModelForm):
# create meta class
class Meta:
# specify model to be used
model = GeeksModel
# specify fields to be used
fields = [
"title",
"description",
]
Create View
Create View refers to a view (logic) to create an instance of a table in the database. It is just like taking an input from a user and storing it in a specified table.Â
In geeks/views.py,Â
Python
from django.shortcuts import render
# relative import of forms
from .models import GeeksModel
from .forms import GeeksForm
def create_view(request):
# dictionary for initial data with
# field names as keys
context = {}
# add the dictionary during initialization
form = GeeksForm(request.POST or None)
if form.is_valid():
form.save()
context['form'] = form
return render(request, "create_view.html", context)
Create a template in templates/create_view.html,Â
html
<form method="POST" enctype="multipart/form-data">
<!-- Security token -->
{% csrf_token %}
<!-- Using the formset -->
{{ form.as_p }}
<input type="submit" value="Submit">
</form>
Now visit http://localhost:8000/Â

To check complete implementation of Function based Create View, visit Create View – Function based Views Django.
Retrieve View
Retrieve view is basically divided into two types of views Detail View and List View. Â
List View
List View refers to a view (logic) to list all or particular instances of a table from the database in a particular order. It is used to display multiple types of data on a single page or view, for example, products on an eCommerce page.Â
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>
Now visit http://localhost:8000/

To check complete implementation of Function based List View, visit List View - Function based Views DjangoÂ
Detail View
Detail View refers to a view (logic) to display a particular instance of a table from the database with all the necessary details. It is used to display multiple types of data on a single page or view, for example, profile of a user.Â
In geeks/views.py, Â
Python3
from django.urls import path
# importing views from views..py
from .views import detail_view
urlpatterns = [
path('<id>', detail_view ),
]
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
# pass id attribute from urls
def detail_view(request, id):
# dictionary for initial data with
# field names as keys
context ={}
# add the dictionary during initialization
context["data"] = GeeksModel.objects.get(id = id)
return render(request, "detail_view.html", context)
Create a template in templates/Detail_view.html,Â
html
<div class="main">
<!-- Specify fields to be displayed -->
{{ data.title }}<br/>
{{ data.description }}<br/>
</div>
Let's check what is there on http://localhost:8000/1Â

To check complete implementation of Function based Detail View, visit Detail View – Function based Views Django
Update View
Update View refers to a view (logic) to update a particular instance of a table from the database with some extra details. It is used to update entries in the database for example, updating an article at geeksforgeeks.Â
In geeks/views.py,
Python3
from django.shortcuts import (get_object_or_404,
render,
HttpResponseRedirect)
# relative import of forms
from .models import GeeksModel
from .forms import GeeksForm
# after updating it will redirect to detail_View
def detail_view(request, id):
# dictionary for initial data with
# field names as keys
context ={}
# add the dictionary during initialization
context["data"] = GeeksModel.objects.get(id = id)
return render(request, "detail_view.html", context)
# update view for details
def update_view(request, id):
# dictionary for initial data with
# field names as keys
context ={}
# fetch the object related to passed id
obj = get_object_or_404(GeeksModel, id = id)
# pass the object as instance in form
form = GeeksForm(request.POST or None, instance = obj)
# save the data from the form and
# redirect to detail_view
if form.is_valid():
form.save()
return HttpResponseRedirect("/"+id)
# add form dictionary to context
context["form"] = form
return render(request, "update_view.html", context)
Now create following templates in templates folder,Â
In geeks/templates/update_view.html,
html
<div class="main">
<!-- Create a Form -->
<form method="POST">
<!-- Security token by Django -->
{% csrf_token %}
<!-- form as paragraph -->
{{ form.as_p }}
<input type="submit" value="Update">
</form>
</div>
In geeks/templates/detail_view.html,Â
html
<div class="main">
<!-- Display attributes of instance -->
{{ data.title }} <br/>
{{ data.description }}
</div>
Let's check if everything is working, visit: http://localhost:8000/1/update.Â

To check complete implementation of Function based update View, visit Update View – Function based Views Django
Delete View
Delete View refers to a view (logic) to delete a particular instance of a table from the database. It is used to delete entries in the database for example, deleting an article at geeksforgeeks.Â
In geeks/views.pyÂ
Python3
from django.shortcuts import (get_object_or_404,
render,
HttpResponseRedirect)
from .models import GeeksModel
# delete view for details
def delete_view(request, id):
# dictionary for initial data with
# field names as keys
context ={}
# fetch the object related to passed id
obj = get_object_or_404(GeeksModel, id = id)
if request.method =="POST":
# delete object
obj.delete()
# after deleting redirect to
# home page
return HttpResponseRedirect("/")
return render(request, "delete_view.html", context)
Now a url mapping to this view with a regular expression of id,Â
In geeks/urls.pyÂ
Python3
from django.urls import path
# importing views from views..py
from .views import delete_view
urlpatterns = [
path('<id>/delete', delete_view ),
]
Template for delete view includes a simple form confirming whether user wants to delete the instance or not. In geeks/templates/delete_view.html,Â
html
<div class="main">
<!-- Create a Form -->
<form method="POST">
<!-- Security token by Django -->
{% csrf_token %}
Are you want to delete this item ?
<input type="submit" value="Yes" />
<a href="/">Cancel </a>
</form>
</div>
Everything ready, now let's check if it is working or not, visit http://localhost:8000/2/deleteÂ

To check complete implementation of Function based Delete View, visit Delete View – Function based Views Django
Â
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