Django Class-Based Views

Learn via video courses
Topics Covered

Overview

Django follows the Model Template View(MVT) architecture. According to Django documentation, the view function is a Python function that takes a web request and returns a web response. The response can be HTML content of a web page, a 404 error, a redirect, an image, an XML document, etc. It is the user interface, that displays the content of the webpage when we render a website. It is represented by HTML/CSS/Javascript. In the views.py file, we create a view function and link the HTML file we created. This view function is in turn linked in the urls.py file with the path. There are two types of views, function-based view , and class-based view.

Pre-requisites

Before moving on to an introduction to Django class-based view, you must first meet the following prerequisites:

  • How to create a basic project in Django?
  • How to create an app in Django?

Introduction to Class-Based views

Django Class-Based Views is a sophisticated set of built-in views used to implement selective view strategies such as Create, Retrieve, Update, and Delete. It implements views as Python objects and not as functions. It provides a class instance method as_view(). In each generic view, the as_view() class instance method creates a connection for calling the class as if it were a method. Well, a method is a label that can be applied to an object; it is a piece of code that can be executed on that object. Certain advantages of the same are listed below:

  • Code organization related to HTTP methods like GET, POST, etc. can be addressed by separate methods instead of conditional branching.
  • A view class in CBV can be inherited by another and modified for a different use case.

A function-based view with a huge number of lines of code can be converted into a class-based view containing few lines only.

Perform CRUD (Create, Retrieve, Update, Delete) Using Class Based Views

In this section, we will elaborate on the execution of Django Class-based Views. CRUD is an acronym that stands for Create, Retrieve, Update and Delete. Let us describe what each of these means.

1. CreateView: Create or add new entries to a database table.

2. RetrieveView: To display multiple instances of a database table or to display a particular instance of a database table.

3. UpdateView: Update or modify existing database entries in a table.

4. DeleteView: Remove a particular instance in a database table.

5. FormView: Render a form to a template and handle user data.

Let us begin by creating a project Glitten and App World. After this, we will create models in the models.py file.

After creating the model we need to run the following commands in the command prompt.

As we know in the above commands, 'make migrations' is responsible for packing up the changes into individual migration files, and 'migrate' is responsible for applying those to our database.

After creating the model we need to create the model form. We create a file named forms.py in the World folder. In the forms.py file,

In the above code,

  • We import the forms and model Glitten.
  • We create a form GlittenForm.
  • We create a metaclass inside it. The Meta class can be used to define the model's permissions, database name, singular and plural names, abstraction, ordering, and so on. Using Meta classes for Django models is optional.
  • We select the model to be used in the variable model.
  • We also select the fields to be used.

In the views.py file,

In the above code,

  • We import HttpResponse and view.
  • We create a view function first.
  • We create a function get, to receive data from the server.
  • We return HttpResponse.

In the urls.py,

In the above code,

  • We import the view first.
  • We link the view first in the path.
  • Since we are using class-based view, as_views() is used.

1. CreateView

CreateView refers to entering an instance of a Database table. Class Based Views alphabetically arrange data from A to Z. We need to specify the model for which we are creating the create view. Django Class-based CreateView will automatically try to find a template in app_name/modelname_form.html. In our case it is World/templates/World/Glitten_form.html.

In the views.py file,

In the above code,

  • We import CreateView and model Glitten.
  • We create a creatview GlittenCreate.
  • We select the model for which we are creating create views.
  • We select the fields.

In the urls.py file,

Now we create a template in templates/World/Glitten_form.html.

We can check it on http://localhost:8000/, and enter instances of the database table.

2. RetrieveView

While retrieving data, we can either display multiple instances of the database table or we can display a single instance. Depending on the above choice, we have a list view and a detail view.

  • List View A ListView is a view that displays multiple instances of a table from the database. In the views.py file,

In the above code,

  • We import ListView and Glitten.
  • We create a ListView.
  • We select the model whose instances we want to display.

In the urls.py file,

We create a template in templates/World/Glitten_list.html,

  • DetailView

A DetailView is a view that displays one instance of a table from the database.

In the views.py file,

In the above code,

  • We import DetailView and model Glitten.
  • We create a DetailView GlittenDetail.
  • We select the model whose single instance we want to display.

In the urls.py,

In the above code,

  • We import GlittenDetail.
  • We link view GlittenDetail in the path. <pk>/ is used for the identification of the id field. The URL path is linked based on the unique id of the instance chosen to be displayed.

We create a template in templates/World/Glitten_detail.html,

3. UpdateView

UpdateView refers to updating or editing a particular instance of a Database table.

In the views.py file,

In the urls.py,

We create a template in templates/World/Glitten_form.html,

Context and Template Responses

Well before getting into context and template responses, we must know what is a mixin. A mixin is another class you create and from which your view class can inherit methods. Assume you want the template's extra variable 'heading' to appear in every view. Using this method, you create a mixin and let your views inherit instead of overriding the get context data method each time you develop the view.

Template Response

According to Django documentation, TemplateResponseMixin provides a render_to_response() method called by TemplateResponse which every built-in view returns. Most of the time, this will be called for you (for example, by the get() method implemented by both TemplateView and DetailView); similarly, it's unlikely that you'll need to override it, though you should if you want your response to return something that isn't rendered using a Django template.

Context

Every built-in view that requires context data, such as when rendering a template (including the TemplateResponseMixin mentioned above), should call get_context_data(), passing any data they want to ensure is present as keyword arguments. get_context_data() returns a dictionary; in Context Mixin, it returns its keyword arguments, but it is common to override this to add more dictionary members.

Django’s Class-based View Mixins (SingleObjectMixin with View and List View)

SingleObjectMixin with View

In the views.py file,

  • If we want to create a class-based view that only responds to POST, we'll subclass View and add a post() method.
  • *args is used to pass an arbitrary number of arguments to a function.
  • **kwargs is used to display instances in key-value pair.
  • The only part of the view that requires SingleObjectMixin is where we want to look up the title we're interested in, which it does with a call to self.get_object().

In the urls.py,

SingleObjectMixin with ListView

SingleObjectMixin implements a mechanism for locating an object related to the current HTTP request. For SingleObjectMixin with ListView, let us assume we have a project named books. We need to have two different querysets:

  1. Book queryset for use by ListView.
  2. Publisher queryset for use in get_object().

In the views.py,

In the above code,

  • We imported a model Publisher.
  • We selected the template.
  • We return a method in the def get(), context in def get_context_data(), all objects in def get_queryset.

FormMixin

Form mixin is a mixin class that allows you to create and display forms. Let us track a user's interest in a specific author, let us say we want to let them leave a message explaining why they like them. We are not going to store this using a relational database, but rather in something more esoteric that we won't worry about. We'll keep the DetailView GET handling, but we'll need to add a Form to the context data so we can render it in the template.

In the above code,

  • Here, we would record the user's interest using the message.

Class-Based vs Function-Based Views

Class-Based ViewFunction-Based View
Complex to implement and readEasy to implement and read.
Implicit code flow.Explicit code flow.
View decorators require an additional import or method override.Decorators are simple to use.
Mixins can be used to add more functionalities.Mixins cannot be used.

Conclusion

Hello Developer!! By now you must have understood what Django class-based view is. Let us summarize what we have learned so far

  • Django Class-Based Views are a sophisticated set of built-in views used to implement selective view strategies such as Create, Retrieve, Update, and Delete.
  • A view class in CBV can be inherited by another and modified for a different use case.
  • CRUD is an acronym that stands for Create, Retrieve, Update and Delete.
  • CreateView refers to entering an instance of a Database table.
  • Class Based Views alphabetically arrange data from A to Z.
  • In retrieveview, we can either display multiple instances of the database table or we can display a single instance.
  • A ListView is a view that displays multiple table instances from the database.
  • A DetailView is a view that displays one instance of a table from the database.
  • UpdateView refers to updating or editing a particular instance of a Database table.
  • A mixin is another class you create and from which your view class can inherit methods.