0% found this document useful (0 votes)
10 views12 pages

CBV Notes - 241127 - 175308

The document discusses Django's class-based views (CBVs) as an alternative to function-based views, highlighting their advantages such as better organization of code and the use of object-oriented techniques. It covers various types of CBVs, including TemplateView, FormView, ListView, DetailView, CreateView, UpdateView, and DeleteView, along with their functionalities and examples. Additionally, it emphasizes best practices for using these views, such as avoiding hard-coded paths and using the get_absolute_url method for generating canonical URLs.

Uploaded by

dp971347
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views12 pages

CBV Notes - 241127 - 175308

The document discusses Django's class-based views (CBVs) as an alternative to function-based views, highlighting their advantages such as better organization of code and the use of object-oriented techniques. It covers various types of CBVs, including TemplateView, FormView, ListView, DetailView, CreateView, UpdateView, and DeleteView, along with their functionalities and examples. Additionally, it emphasizes best practices for using these views, such as avoiding hard-coded paths and using the get_absolute_url method for generating canonical URLs.

Uploaded by

dp971347
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Important points regarding views:

----------------------------------
1. A view is a callable which takes a request and returns a response.
2. This can be more than just a function, and Django provides an example
of some classes which can be used as views

Class-based views:
------------------
1. Class-based views provide an alternative way to implement views as
Python objects instead of functions.
2. CBV do not replace function-based views, but they have certain differences and
advantages when compared to function-based views

The differences are:


--------------------
1. Organization of code related to specific HTTP methods (GET, POST, etc.)
can be addressed by separate methods instead of conditional branching.
2. Object oriented techniques such as mixins (multiple inheritance) can be
used to factor code into reusable components.

Key points we have to follow when we r writing CBV:


--------------------------------------------------
1. Each and Every CBV must be inherited from any one of the View classes of
Django
2. Url of CBV is created by using below syntax

path('suufix/',views.classname.as_view(),name='name of the url')

Some Of the View Classes of django along with their module name:
---------------------------------------------------------------
view Class_Name location of the view class

1. View django.views.generic
2. TemplateView django.views.generic
3. ListView django.views.generic
4. DetailView django.views.generic
5. FormView django.views.generic
6. CreateView django.views.generic
7. UpdateView django.views.generic
8. DeleteView django.views.generic

View Class:
------------
first we have import View class by below syntax
from django.views.generic import View

Responding some data with View class:


-------------------------------------
views.py file:
--------------
# function based view:

def Functionnamae(request):
return HttpResponse('data')

# class based View:

class Class_Name(View):
def get(self,request):
return HttpResponse('data')

Responding Html Files:


-----------------------
#Function Based view for responding a html with form as context

def FBV_html(request):
form=forms.Student()
if request.method=='POST':
form_data=forms.Student(request.POST)
if form_data.is_valid():
print(form_data.cleaned_data)
return HttpResponse('Form is valid')
return render(request,'fbv.html',context={'form':form})

#Class Based view for responding a html with form as context

class CBV_html(View):
def get(self,request):
form=forms.Student()
return render(request,'fbv.html',context={'form':form})

def post(self,request):
form_data=forms.Student(request.POST)
if form_data.is_valid():
print(form_data.cleaned_data)
return HttpResponse('Form is valid')

Note:
-----
It is advised not to use View Class when we r dealing with Html files and
Forms instead use TemplateView and FormView to reduce Code complexity

TemplateView:
-------------
1. The Django generic TemplateView view class enables developers to quickly
create views that display simple templates without reinventing the wheel

2. Instead of extending View, override the get method and then process the
template and return an HttpResponse object using a render function.
3. Simpy extend TemplateView when we r dealing with Html files

first we have to import View class by below syntax:


----------------------------------------------------
from django.views.generic import TemplateView

Rendering a Normal html file with TemplateView view class:


---------------------------------------------------------

class Class_name(TemplateView):
template_name='name_of_the template'

Using TemplateView in urls.py:


-------------------------------
1. you can use TemplateView directly in your URL. This provides you with
a quicker way to render a template
2. in this case there is no need of creating any class inside views
directly we can write in Urls
3. in this type we have to import TemplateView into urls

syntax of url in Urls.py file:


-------------------------------
from django.views.generic import TemplateView

urlpatterns=[
path('suffix/',TemplateView.as_view(template_name='name_of_the_template']
]
Django Template Context with TemplateView:
-------------------------------------------
1. If u r using TemplateView, you need to use the get_context_data method to
provide any context data variables to your template.
2. After that we have to re-define the get_context_data method and provide
an implementation which simply gets a context dict object from the parent
class (in this example it's TemplateView) then augments it by passing the
message data.

example:
--------

class Template(TemplateView):
template_name='templateview.html'

def get_context_data(self, **kwargs):


context = super().get_context_data(**kwargs)
#context["data"]='hai hello how r u'
context['form']=forms.Student()
return context

def post(self,request):
form_data=forms.Student(request.POST)
if form_data.is_valid():
print(form_data.cleaned_data)
return HttpResponse('Form is valid')

Note:
-----
1. TemplateView shouldn’t be used when your page has forms and does creation
or update of objects.
2. In such cases FormView, CreateView or UpdateView is a better option.

FormView:
---------
1. FormView should be used when you need a form on the page and want to
perform certain action when a valid form is submitted.

2. we use form_class attribute to specify form class

3. we use form_valid method inorder to validate and perform some opearations


on submitted data
first we have to import View class by below syntax:
----------------------------------------------------
from django.views.generic import FormView

# creating a CBV with FormView view class


------------------------------------------
class Form(FormView):
form_class=forms.Student # specifying the Form class you want to use
template_name='templateview.html' #sepcify name of template

def form_valid(self,form):
data=form.cleaned_data
return HttpResponse(str(data))

# creating a CBV with FormView view class and saving data into database:
------------------------------------------------------------------------
class FormModel(FormView):
form_class=forms.TopicForm # specifying the Form class you want to use
template_name='templateview.html' #sepcify name of template

def form_valid(self,form):
form.save()
return HttpResponse('Form is sumitted successfully')

Generic display views:


----------------------
Django has Two generic class-based views which are designed to display data
1. ListView
2. DetailedView

ListView:
---------
1. ListView should be used when you want to present a list of objects in a
html page.
2. ListView can achieve everything which TemplateView can do with less code.

first we have to import View class by below syntax:


----------------------------------------------------
from django.views.generic import ListView
attributes of list view:
------------------------
model ------->to specify model name(by default it fetch all data)
queryset ----->it is used to specify filtering of model data
context_object_name ----->it specifies context name
template_name ----->it is used specify the Html file file to render
ordering -----> It is used order the data based on columns

Example:
--------
class CBV_listview(ListView):
model=School
#queryset=School.objects.filter(name='QSPIDERS')
template_name='list.html'
context_object_name='schools'
ordering = ['name']

School_list.html file content:


------------------------------
{% extends "myapp/base.html" %}

{% block body_block %}
<div class="jumbotron">
<h1>Schools Are : </h1>
{% if schools %}
<ol>
{% for school in schools%}
<li><a href="{{school.id}}">{{school}}</a></h1></li>
{% endfor %}
</ol>

{% else %}
<h1>No School Found</h1>
{% endif %}

</div>
{% endblock %}

2. DetailView:
-------------
1. DetailView should be used when you want to represent detail of a single
model instance.

important points to remember:


-----------------------------
1. First of all, when it comes to web development you really want to avoid hard
coding paths in your templates.
2. The reason for this is that paths will be different for each and every
instances of the model
3. so it becomes very difficult to find out and change each and every url path
manually
4. So we have to define function which is responsible for returning the URL paths
based on selected model instance
5. This can be done by using get_absolute_url method

get_absolute_url():
-------------------
1. get_absolute_url() method is used to tell Django how to create the canonical
URL for an model object by providing model instance reference.
1. A canonical URL is "the official" url to a certain page.

2. get_absolute_url method must be defined inside the model class as shown below
along with reverse function of url

models.py content:
------------------
from django.db import models
from django.urls import reverse

# Create your models here.

class School(models.Model):
name=models.CharField(max_length=100)
principal=models.CharField(max_length=100)
location=models.CharField(max_length=100)

def __str__(self):
return self.name

def get_absolute_url(self):
return reverse("detail",kwargs={"pk": self.pk})

class Student(models.Model):
name=models.CharField(max_length=100)
age=models.PositiveIntegerField()
school=models.ForeignKey(School,on_delete=models.CASCADE,related_name="students")

def __str__(self):
return self.name

School_detail.html content:
---------------------------
{% extends "myapp/base.html" %}

{% block body_block %}<div class="container">


<div class="jumbotron">
<h1>School Details Are : </h1>
<table border="2pt">
<tr>
<th>Name</th>
<th>Principal</th>
<th>Location</th>
</tr>
<tr>
<td>{{school.name}}</td>
<td>{{school.principal}}</td>
<td>{{school.location}}</td>
</tr>
</table>
</div>
<div class="jumbotron">
<h1>Students Details are : </h1>
{% for student in school.students.all %}
<h3>Student Name : {{student.name}} Age : {{student.age}}</h3>
{% endfor %}
</div>
<a href="{% url 'myapp:update' pk=school.pk %}" class="btn btn-warning">Update</a>
<a href="{% url 'myapp:delete' pk=school.pk %}" class="btn btn-warning">Delete</a>
</div>
{% endblock %}

Using regular expressions in defining urls:


-------------------------------------------
1. For creating cananical urls based selected model instance we cannot give
exact values instead we have to define a pattern
2. that can be done by using
Python regular expressions, the syntax for named regular expression groups is

(?P<name>pattern)

where ?P ------>is to capture the contents of <>


name ---->it is the name by using which we can access content
pattern---->it is some pattern to match.

3. In-order to create urls with regular expressions we have to use


re_path instead of path function

example:
-------
from django.urls import re_path

urlpatterns=[
re_path('(?P<pk>\d+)/',views.classname.as_view(),name='name'),
]

Editing Views:
--------------
Django has Three generic class-based views which are designed to Edit the data
1. CreateView
2. UpdateView
3. DeleteView

CreateView:
-----------
1. CreateView should be used when you need a form on the page and need to do
a db insertion on submission of a valid form.
2. A view that displays a form for creating an object, redisplaying the form
with validation errors (if there are any) and saving the object.
3. The CreateView page displayed to a GET request uses a
template_name_suffix of '_form'
4. so create a html file with modelname_form.html so that CreateView will
automatically render that file without even mentioning template_name

Example:
--------
class SchoolCreateView(CreateView):
model=School
#fields='__all__' (fields functionality is same as in Meta class)
fields=('name','principal','location')

school_form.html content:
-------------------------
{% extends "myapp/base.html" %}

{% block body_block %}
<h1>Creaate School By Filling Form : </h1>

<form method="POST">
{% csrf_token %}
{{form.as_p}}
<input type="submit" value="Create" class="btn btn-primary">

</form>
{% endblock %}

UpdateView:
-----------
1. A view that displays a form for editing an existing object, redisplaying
the form with validation errors (if there are any) and saving changes
to the object.
2. This uses a form automatically generated from the object’s model class
(unless a form class is manually specified).

3. The UpdateView page displayed to a GET request uses a


template_name_suffix of '_form'

views.py:
---------
class SchoolUpdateView(UpdateView):
model=School
fields=('name','principal','location')

Using same school_form.html file with some changes:


----------------------------------------------------

{% extends "myapp/base.html" %}

{% block body_block %}
{% if form.instance.pk %}
<h1>Update The Details</h1>
{% else %}
<h1>Creaate School By Filling Form : </h1>
{% endif %}

<form method="POST">
{% csrf_token %}
{{form.as_p}}
{% if form.instance.pk %}
<input type="submit" value="Update" class="btn btn-warning">
{% else %}
<input type="submit" value="Create" class="btn btn-primary">
{% endif %}

</form>
{% endblock %}

urls.py:
--------
re_path('^update/(?P<pk>\d+)/',views.SchoolUpdateView.as_view(),name="update"),

DeleteView:
-----------
1. A view that displays a confirmation page and deletes an existing object.
2. The given object will only be deleted if the request method is POST.
3. If this view is fetched via GET, it will display a confirmation page that
should contain a form that POSTs to the same URL.
4. The DeleteView page displayed to a GET request uses a
template_name_suffix of '_confirm_delete'.

views.py:
---------
from django.urls import reverse_lazy

class SchoolDeleteView(DeleteView):
model=School
context_object_name="school"
success_url=reverse_lazy('myapp:list')

school_confirm_delete.html content:
-----------------------------------
{% extends "myapp/base.html" %}

{% block body_block %}
<h1>Are Your Sure In Deleting {{school}} ?</h1>
<form method="POST">
{% csrf_token %}
<input type="submit" value="Delete" class="btn btn-security">
<a href="{% url 'myapp:list' %}" class="btn btn-primary">Cancel</a>

</form>
{% endblock %}

urls.py:
--------
re_path('^delete/(?P<pk>\d+)/',views.SchoolDeleteView.as_view(),name="delete"),

https://docs.djangoproject.com/en/3.0/topics/class-based-views/generic-editing/

You might also like