Using and Customizing Generic Views in Django

Learn via video courses
Topics Covered

Overview

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. 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.

Built-in Class-based Generic Views

Extending Generic Views

To extend the generic views it is advised to subclass generic views and override their properties or methods rather than passing in a lot of configuration information in the URLconf.

Generic Views of Objects

Using and customizing generic views in django is always a good idea to present views of our database content. A few common views that are already included with Django can be used to create lists and detail views of objects. Let us consider an example.

In the models.py file,

Let us now see the views.py file,

In the urls.py file,

We can also make a template and add it to the view by using the attribute template_name.

i. Making “friendly” template contexts:

In the template, we used to variable obj_list to store the list of all the authors. To make the template friendly to the user we can add an attribute context_object_name to the views which would specify the context variable to use in the template. So our views.py would look like this,

ii. Adding extra context:

Say we want to add the list of all the books on each author detail page. So we subclass the detail view and implement the extra context we wish to add under the get_context_data method.

iii. Viewing subsets of objects:

Say we want to get the filtered list of objects. we use the method .order_by().

iv. Dynamic filtering:

Say we want to list the books by a particular author. We use the get_queryset method in the ListView.

In the urls.py file,

In the views.py file,

v. Performing extra work:

Say we want to record the last accessed date for each author. Let us add this extra field last_access.

In the views.py file,

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, 'makemigrations' 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.pyin 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 a 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 createview GlittenCreate.
  • We select the model for which we are creating createviews.
  • 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. Based on the unique id of the instance chosen to be displayed the URL path is linked.

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,

4. DeleteView

This view is used to delete a particular record from the table. In the views.py file,

In the urls.py,

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

5. FormView

Form view is used to verify the Django form and also to display it. In the views.py file,

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

In the urls.py,

Conclusion

Hello developer!! I am sure by now you must have understood how the Django developers are using and customizing generic views in Django. Let us summarize what we have learned so far,

  • 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 provides a class instance method as_view().
  • Using and customizing generic views in django is always a good idea to present views of our database content.
  • CreateView:
    Create or add new entries to a database table.
  • RetrieveView:
    To display multiple instances of a database table or to display a particular instance of a database table.
  • UpdateView:
    Update or modify existing database entries in a table.
  • DeleteView:
    Remove a particular instance in a database table.
  • FormView:
    Render a form to a template and handle user data.