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 is a Python framework that simplifies web development by handling complex tasks for you. It follows the "Don't Repeat Yourself" (DRY) principle, promoting reusable components and making development faster. With built-in features like user authentication, database connections, and CRUD operati
10 min read
Django Basics
Django Basics
Django is a Python-based web framework which allows us to quickly develop robust web application without much third party installations. It comes with many built-in featuresâlike user authentication, an admin panel and form handlingâthat help you build complex sites without worrying about common web
3 min read
Django Installation and Setup
Installing and setting up Django is a straightforward process. Below are the step-by-step instructions to install Django and set up a new Django project on your system.Prerequisites: Before installing Django, make sure you have Python installed on your system. How to Install Django?To Install Django
2 min read
When to Use Django? Comparison with other Development Stacks
Prerequisite - Django Introduction and Installation Django is a high-level Python web framework which allow us to quickly create web applications without all of the installation or dependency problems that we normally face with other frameworks. One should be using Django for web development in the
2 min read
Django Project MVT Structure
Django follows the MVT (Model-View-Template) architectural pattern, which is a variation of the traditional MVC (Model-View-Controller) design pattern used in web development. This pattern separates the application into three main components:1. ModelModel acts as the data layer of your application.
2 min read
How to Create a Basic Project using MVT in Django ?
Prerequisite - Django Project MVT Structure Assuming you have gone through the previous article. This article focuses on creating a basic project to render a template using MVT architecture. We will use MVT (Models, Views, Templates) to render data to a local server. Create a basic Project: To in
2 min read
How to Create an App in Django ?
In Django, an app is a web application that performs a specific functionality, such as blog posts, user authentication or comments. A single Django project can consist of multiple apps, each designed to handle a particular task. Each app is a modular and reusable component that includes everything n
3 min read
Django settings file - step by step Explanation
Once we create the Django project, it comes with a predefined Directory structure having the following files with each file having its own uses. Let's take an example // Create a Django Project "mysite" django-admin startproject mysite cd /pathTo/mysite // Create a Django app "polls" inside project
3 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 Forms
Django Forms
Django Forms are used to gather input from users, validate that input, and process it, often saving the data to the database. For example, when registering a user, a form collects information like name, email, and password.Django automatically maps form fields to corresponding HTML input elements. I
5 min read
How to Create a form using Django Forms
This article explains how to create a basic form using various form fields and attributes. Creating a form in Django is very similar to creating a model, you define the fields you want and specify their types. For example, a registration form might need fields like First Name (CharField), Roll Numbe
2 min read
Django Form | Data Types and Fields
When collecting user input in Django, forms play a crucial role in validating and processing the data before saving it to the database. Django provides a rich set of built-in form field types that correspond to different kinds of input, making it easy to build complex forms quickly.Each form field t
4 min read
Django Form | Build in Fields Argument
We utilize Django Forms to collect user data to put in a database. For various purposes, Django provides a range of model field forms with various field patterns. The most important characteristic of Django forms is their ability to handle the foundations of form construction in only a few lines of
3 min read
Python | Form validation using django
Prerequisites: Django Installation | Introduction to DjangoDjango works on an MVT pattern. So there is a need to create data models (or tables). For every table, a model class is created. Suppose there is a form that takes Username, gender, and text as input from the user, the task is to validate th
5 min read
Render Django Form Fields Manually
Django form fields have several built-in methods to ease the work of the developer but sometimes one needs to implement things manually for customizing User Interface(UI). We have already covered on How to create and use a form in Django?. A form comes with 3 in-built methods that can be used to ren
5 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
User Groups with Custom Permissions in Django - Python
Our task is to design the backend efficiently following the DRY (Don't Repeat Yourself) principle, by grouping users and assigning permissions accordingly. Users inherit the permissions of their groups.Let's consider a trip booking service, how they work with different plans and packages. There is a
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
Extending and customizing django-allauth in Python
Django-allauth is a powerful Django package that simplifies user authentication, registration, account management, and integration with social platforms like Google, Facebook, etc. It builds on Djangoâs built-in authentication system, providing a full suite of ready-to-use views and forms.Prerequisi
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