CBV Notes - 241127 - 175308
CBV Notes - 241127 - 175308
----------------------------------
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
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
def Functionnamae(request):
return HttpResponse('data')
class Class_Name(View):
def get(self,request):
return HttpResponse('data')
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 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
class Class_name(TemplateView):
template_name='name_of_the template'
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 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.
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')
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.
Example:
--------
class CBV_listview(ListView):
model=School
#queryset=School.objects.filter(name='QSPIDERS')
template_name='list.html'
context_object_name='schools'
ordering = ['name']
{% 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.
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
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" %}
(?P<name>pattern)
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).
views.py:
---------
class SchoolUpdateView(UpdateView):
model=School
fields=('name','principal','location')
{% 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/