A view function, or “view” for short, is simply a Python function that takes a web request and returns a web response. This response can be the HTML contents of a Web page, or a redirect, or a 404 error, or an XML document, or an image, etc. Example: You use view to create web pages, note that you need to associate a view to a URL to see it as a web page.
In Django, views have to be created in the app views.py file.
Simple View
We will create a simple view in myapp to say "welcome to my app!"
See the following view −
1)
from django.http import HttpResponse def hello(request): text = """<h1>welcome to my app !</h1>""" return HttpResponse(text)
In this view, we use HttpResponse to render the HTML (as you have probably noticed we have the HTML hard coded in the view). To see this view as a page we just need to map it to a URL (this will be discussed in an upcoming chapter).
We used HttpResponse to render the HTML in the view before. This is not the best way to render pages. Django supports the MVT pattern so to make the precedent view, Django - MVT like, we will need −
2)
A template: myapp/templates/hello.html
And now our view will look like −
from django.shortcuts import render def hello(request): return render(request, "myapp/template/hello.html", {})
Views can also accept parameters −
3)
from django.http import HttpResponse def hello(request, number): text = "<h1>welcome to my app number %s!</h1>"% number return HttpResponse(text)
When linked to a URL, the page will display the number passed as a parameter. Note that the parameters will be passed via the URL (discussed in the next chapter).
Cd D:\django\myproject\myapp
Create vi views.py
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
def hello(request):
text = """<h1>welcome to my app !</h1>"""
return HttpResponse(text)
def index(request):
text = """<h1>welcome to my app !</h1>"""
return HttpResponse(text)
###################################################################################
1. Add the following entries in myproject/urls.py
from django.contrib import admin
from django.urls import path,re_path,include
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('hello/',views.hello,name='hello'),
re_path('display(\d+)/',views.display,name='id'),
path('myapp/',include("myapp.urls")),
]
2. create views.py in myproject/myproject /views.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
#Python Functions
def hello(request):
text="""<h1> Hello World </h1>"""
return HttpResponse(text)
def display(request,id):
text="Algorithm Class, Hyderabad, Batch:48 %s"%id
return HttpResponse(text)
Hierarchical URL
Cd D:\django\myproject\myapp
- Create vi views.py
######NEW########
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
#Python Functions
def hello_myapp(request):
text="""<h1> Hello World Myapp</h1>"""
return HttpResponse(text)
def hello_myapp2(request):
text="""<h1> Hello World Myapp2</h1>"""
return HttpResponse(text)
2. Create myapp/urls.py
from django.contrib import admin
from django.urls import path,re_path,include
from . import views
urlpatterns = [
path('', views.hello_myapp,name='hello_myapp' ),
path('hi/', views.hello_myapp2,name='hello_myapp2' ),
]
######NEW########
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
#Using HttpResponse and without using .html file
def hello(request):
text="""<h1> Welcome to my app </h1>"""
return HttpResponse(text)
#Using render using .html file
D:\lab\batch31\myproject\myapp\templates\hello.html
def hello(request):
return render(request, "hello.html", {})
# Accepting Arguments in views
def hello2(request,id):
text = "Displaying article Number : %s"%id
return HttpResponse(text)
# Passing arguments to html
D:\lab\batch31\myproject\myapp\templates\hello2.html
def hello3(request,id):
return render(request, "hello2.html", {"today" : id})
vi myproject/urls.py and add the following lines
from django.contrib import admin
from django.urls import path,include
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('display/', views.hello,name='hello'),
path('myapp/', include('myapp.urls')),
]
** Create new file urls.py in myapp
vi myproject/myapp/urls.py and add the following lines
Note: we have to use re_path with regular expressions
from django.contrib import admin
from django.urls import path,re_path
from . import views
urlpatterns = [
#'myapp.views',
#path('admin/', admin.site.urls),
path('', views.hello,name='hello1'),
re_path('display(\d+)', views.hello2,name='id'),
re_path('temp(\d+)', views.hello3,name='id'),
]
Create folder templates
cd D:\lab\batch31\myproject\myapp\templates
vi hello2.html
<html>
<body>
Hello World!!!<p>Today is {{today}}</p>
</body>
</html>
###################################################################################
Django Views are one of the vital participants of MVT Structure of Django. A View is the user interface — what you see in your browser when you render a website. It is represented by HTML/CSS/Javascript and Jinja files. 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, or a redirect, or a 404 error, or an XML document, or an image, anything that a web browser can display.
Django View Example
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
,
# 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
,
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.
Types of Views
Django views are divided into two major categories :-
- Function Based Views
- Class Based Views
Function Based Views
Function based views are writer using a function in python which recieves 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.
Function based view Example –
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
,
# 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
,
from django.contrib import admin from .models import GeeksModel # Register your models here. admin.site.register(GeeksModel) |
Now we have everything ready for back end. Verify that instnaces have been created from http://localhost:8000/admin/geeks/geeksmodel/
Let’s create a view and template for the same. In geeks/views.py
,
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
,
< 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 :-
Create View – Function based Views Django
Detail View – Function based Views Django
Update View – Function based Views Django
Delete View – Function based Views Django
Class Based Views
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 a class-based views with few lines only. This is where Object-Oriented Programming comes into impact.
Class based view Example –
In geeks/views.py
,
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,
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
,
< 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 :-
Django CRUD (Create, Retrieve, Update, Delete) 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, 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 CRUD (Create, Retrieve, Update, Delete) Function Based Views
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
,
# 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,
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
,
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
,
< 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,
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
,
< 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 instnace 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
,
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
,
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
,
< 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 enteries in the database for example, updating an article at geeksforgeeks.
In geeks/views.py
,
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
,
< 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
,
< div class = "main" > <!-- Display attributes of instance --> {{ data.title }} < br /> {{ data.description }} </ div > |
Let’s check if everything is working, visithttp://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
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
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
,
< 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
- Difficulty Level : Basic
- Last Updated : 20 Jul, 2020
Django is a Python-based web framework that allows you to quickly create web applications. It has built-in admin interface which makes easy to work with it. It is often called Batteries included framework because it provides built-in facilities for every functionality. Class Based Generic Views are advanced set of Built-in views which are used for implementation of selective view strategies such as Create, Retrieve, Update, Delete. Class based views simplify the use by separating GET, POST requests for a view. 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.
This article revolves around complete implementation of Class Based Views in Django (Create, Retrieve, Update, Delete). Let’s discuss what actually CRUD means,
CreateView – create or add new entries in a table in the database.
Retrieve Views – read, retrieve, search, or view existing entries as a list(ListView) or retrieve a particular entry in detail (DetailView)
UpdateView – update or edit existing entries in a table in the database
DeleteView – delete, deactivate, or remove existing entries in a table in the database
FormView – render a form to template and handle data entered by user
Django CRUD (Create, Retrieve, Update, Delete) Class Based Views
Illustration of How to create and use CRUD views 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
,
# 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,
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" , ] |
Using Class Based Views
At its core, a class-based view allows you to respond to different HTTP request methods with different class instance methods, instead of with conditionally branching code inside a single view function.
So where the code to handle HTTP GET in a view function would look something like:
from django.http import HttpResponse def my_view(request): if request.method = = 'GET' : # <view logic> return HttpResponse( 'result' ) |
In a class-based view, this would become:
from django.http import HttpResponse from django.views import View class MyView(View): def get( self , request): # <view logic> return HttpResponse( 'result' ) |
Similarly in urls.py
, one needs to use as_view()
method to diffrentiate a class based view from function based view.
# urls.py from django.urls import path from myapp.views import MyView urlpatterns = [ path( 'about/' , MyView.as_view()), ] |
CreateView
Create View refers to a view (logic) to create an instance of a table in the database. We have already discussed basics of Create View in Create View – Function based Views Django. Class Based Views automatically setup everything from A to Z. One just needs to specify which model to create Create View for and the fields. Then Class based CreateView will automatically try to find a template in app_name/modelname_form.html
. In our case it is geeks/templates/geeks/geeksmodel_form.html
. Let’s create our class based view. In geeks/views.py
,
from django.views.generic.edit import CreateView from .models import GeeksModel class GeeksCreate(CreateView): # specify the model for create view model = GeeksModel # specify the fields to be displayed fields = [ 'title' , 'description' ] |
Now create a url path to map the view. In geeks/urls.py,
from django.urls import path # importing views from views..py from .views import GeeksCreate urlpatterns = [ path('', GeeksCreate.as_view() ), ] |
Create a template in templates/geeks/geeksmodel_form.html
,
< form method = "POST" enctype = "multipart/form-data" > <!-- Security token --> {% csrf_token %} <!-- Using the formset --> {{ form.as_p }} < input type = "submit" value = "Submit" > </ form > |
Let’s check what is there on http://localhost:8000/
To check complete implementation of Class based CreateView, visit Createview – Class Based Views Django.
Retrieve Views
ListView
List View refers to a view (logic) to display multiple instances of a table in the database. We have already discussed basics of List View in List View – Function based Views Django. Class Based Views automatically setup everything from A to Z. One just needs to specify which model to create ListView for, then Class based ListView will automatically try to find a template in app_name/modelname_list.html
. In our case it is geeks/templates/geeks/geeksmodel_list.html
. Let’s create our class based view. In geeks/views.py
,
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,
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
,
< 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/
To check complete implementation of Class based ListView, visit ListView – Class Based Views Django
DetailView
Detail View refers to a view (logic) to display one instances of a table in the database. We have already discussed basics of Detail View in Detail View – Function based Views Django. Class Based Views automatically setup everything from A to Z. One just needs to specify which model to create DetailView for, then Class based DetailView will automatically try to find a template in app_name/modelname_detail.html
. In our case it is geeks/templates/geeks/geeksmodel_detail.html
. Let’s create our class based view. In geeks/views.py
,
from django.views.generic.detail import DetailView from .models import GeeksModel class GeeksDetailView(DetailView): # specify the model to use model = GeeksModel |
Now create a url path to map the view. In geeks/urls.py,
from django.urls import path # importing views from views..py from .views import GeeksDetailView urlpatterns = [ # <pk> is identification for id field, # slug can also be used path( '<pk>/' , GeeksDetailView.as_view()), ] |
Create a template in templates/geeks/geeksmodel_detail.html
,
< h1 >{{ object.title }}</ h1 > < p >{{ object.description }}</ p > |
Let’s check what is there on http://localhost:8000/1/
To check complete implementation of Class based DetailView, visit DetailView – Class Based Views Django
UpdateView
UpdateView 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 enteries in the database for example, updating an article at geeksforgeeks. We have already discussed basics of Update View in Update View – Function based Views Django. Class Based Views automatically setup everything from A to Z. One just needs to specify which model to create UpdateView for, then Class based UpdateView will automatically try to find a template in app_name/modelname_form.html
. In our case it is geeks/templates/geeks/geeksmodel_form.html
. Let’s create our class based view. In geeks/views.py
,
# import generic UpdateView from django.views.generic.edit import UpdateView # Relative import of GeeksModel from .models import GeeksModel class GeeksUpdateView(UpdateView): # specify the model you want to use model = GeeksModel # specify the fields fields = [ "title" , "description" ] # can specify success url # url to redirect after successfully # updating details success_url = "/" |
Now create a url path to map the view. In geeks/urls.py,
from django.urls import path # importing views from views..py from .views import GeeksUpdateView urlpatterns = [ # <pk> is identification for id field, # <slug> can also be used path( '<pk>/update' , GeeksUpdateView.as_view()), ] |
Create a template in templates/geeks/geeksmodel_form.html
,
< form method = "post" > {% csrf_token %} {{ form.as_p }} < input type = "submit" value = "Save" > </ form > |
Let’s check what is there on http://localhost:8000/1/update/
To check complete implementation of Class based UpdateView, visit UpdateView – Class Based Views Django.
DeleteView
Delete View refers to a view (logic) to delete a particular instance of a table from the database. It is used to delete enteries in the database for example, deleting an article at geeksforgeeks. We have already discussed basics of Delete View in Delete View – Function based Views Django. Class Based Views automatically setup everything from A to Z. One just needs to specify which model to create DeleteView for, then Class based DeleteViewde will automatically try to find a template in app_name/modelname_confirm_delete.html
. In our case it is geeks/templates/geeks/geeksmodel_confirm_delete.html
. Let’s create our class based view. In geeks/views.py
,
# import generic UpdateView from django.views.generic.edit import DeleteView # Relative import of GeeksModel from .models import GeeksModel class GeeksDeleteView(DeleteView): # specify the model you want to use model = GeeksModel # can specify success url # url to redirect after successfully # deleting object success_url = "/" |
Now create a url path to map the view. In geeks/urls.py,
from django.urls import path # importing views from views..py from .views import GeeksDeleteView urlpatterns = [ # <pk> is identification for id field, # slug can also be used path( '<pk>/delete/' , GeeksDeleteView.as_view()), ] |
Create a template in templates/geeks/geeksmodel_confirm_delete.html
,
< form method = "post" >{% csrf_token %} < p >Are you sure you want to delete "{{ object }}"?</ p > < input type = "submit" value = "Confirm" > </ form > |
Let’s check what is there on http://localhost:8000/1/delete
.
To check complete implementation of Class based DeleteView, visit DeleteView – Class Based Views Django
FormView
FormView refers to a view (logic) to display and verify a Django Form. For example a form to register users at geeksforgeeks. Class Based Views automatically setup everything from A to Z. One just needs to specify which form to create FormView for and template_name, then Class based FormView will automatically render that form. Let’s create our class based view. In geeks/views.py
,
# import generic FormView from django.views.generic.edit import FormView # Relative import of GeeksForm from .forms import GeeksForm class GeeksFormView(FormView): # specify the Form you want to use form_class = GeeksForm # sepcify name of template template_name = "geeks / geeksmodel_form.html" # can specify success url # url to redirect after successfully # updating details success_url = "/thanks/" |
Create a template for this view in geeks/geeksmodel_form.html
,
< form method = "post" > {% csrf_token %} {{ form.as_p }} < input type = "submit" value = "Save" > </ form > |
Map a url to this view in geeks/urls.py
,
from django.urls import path # importing views from views..py from .views import GeeksFormView urlpatterns = [ path('', GeeksFormView.as_view()), ] |
Now visit http://127.0.0.1:8000/,
Class based views
myapp/urls.py
path('about/', views.MyView.as_view()), # Class based
path('create/', views.RtiCreate.as_view()),
path('list/', views.RtiList.as_view()),
path('<pk>/detail', views.RtiDetailView.as_view()),
path('<pk>/update',views.RtiUpdateView.as_view()),
path('<id>/delete', views.RtiDeleteView,name="id" ),
path('form', views.RtiFormView.as_view()),
myapp/views.py
# For the above code equivalent class based code
from django.views import View
class MyView(View): # Class based
def get(self, request):
# <view logic>
return HttpResponse('result')
from django.views.generic.edit import CreateView
from .models import RTI
class RtiCreate(CreateView): # Create view
# specify the model for create view
model =RTI
# specify the fields to be displayed
fields = ['rti_no', 'rti_label','rti_lrg','rti_dif','rti_symptom','rti_status']
success_url = "/rti/about"
from django.views.generic.list import ListView
from .models import RTI
class RtiList(ListView):
# specify the model for list view
model = RTI
from django.views.generic.detail import DetailView
from .models import RTI
class RtiDetailView(DetailView):
# specify the model to use
model = RTI
from django.views.generic.edit import UpdateView
from .models import RTI
class RtiUpdateView(UpdateView):
# specify the model for create view
model =RTI
# specify the fields to be displayed
fields = ['rti_no', 'rti_label','rti_lrg','rti_dif','rti_symptom']
success_url = "/rti/about"
from django.views.generic.edit import FormView
from .forms import RtiForm
class RtiFormView(FormView):
# specify the model for create view
model =RtiForm
# sepcify name of template
template_name = "rti_form.html"
success_url = "/rti/about"
myapp/templates/myapp
cat rti_detail.py
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-wEmeIV1mKuiNpC+IOBjI7aAzPcEZeedi5yW5f2yOq55WWLwNGmvvx4Um1vskeMj0" crossorigin="anonymous">
</head>
<body>
<ul>
<table class="table">
<thead>
<tr>
<th scope="col">RTI#</th>
<th scope="col">DIF</th>
<th scope="col">LRG</th>
<th scope="col">SYMPTOM</th>
</tr>
</thead>
<tbody>
<!-- Iterate over object_list -->
<!-- Display Objects -->
<tr>
<td>{{ object.rti_no }}</td>
<td>{{ object.rti_dif }}</td>
<td>{{ object.rti_lrg }}</td>
<td>{{ object.rti_symptom }}</td>
</tr>
</tbody>
</table>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-p34f1UUtsS3wqzfto5wAAmdvj+osOnFyQFpp4Ua3gs/ZVWx6oOypYoCJhGGScy+8" crossorigin="anonymous"></script>
</body>
myapp/template/myapp/rti_form.html
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-wEmeIV1mKuiNpC+IOBjI7aAzPcEZeedi5yW5f2yOq55WWLwNGmvvx4Um1vskeMj0" crossorigin="anonymous">
</head>
<body>
<form method="POST" enctype="multipart/form-data">
<!-- Security token -->
{% csrf_token %}
<!-- Using the formset -->
{{ form.as_p }}
<input type="submit" value="Submit">
</form>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-p34f1UUtsS3wqzfto5wAAmdvj+osOnFyQFpp4Ua3gs/ZVWx6oOypYoCJhGGScy+8" crossorigin="anonymous"></script>
</body>
myapp/template/myapp/rti_list
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-wEmeIV1mKuiNpC+IOBjI7aAzPcEZeedi5yW5f2yOq55WWLwNGmvvx4Um1vskeMj0" crossorigin="anonymous">
</head>
<body>
<ul>
<table class="table">
<thead>
<tr>
<th scope="col">RTI#</th>
<th scope="col">DIF</th>
<th scope="col">LRG</th>
<th scope="col">SYMPTOM</th>
</tr>
</thead>
<tbody>
<!-- Iterate over object_list -->
{% for object in object_list %}
<!-- Display Objects -->
<tr>
<td>{{ object.rti_no }}</td>
<td>{{ object.rti_dif }}</td>
<td>{{ object.rti_lrg }}</td>
<td>{{ object.rti_symptom }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-p34f1UUtsS3wqzfto5wAAmdvj+osOnFyQFpp4Ua3gs/ZVWx6oOypYoCJhGGScy+8" crossorigin="anonymous"></script>
</body>