Django Class Based views

Django Class  Based views

Table of contents

No heading

No headings in the article.

This week i learnt about Django class Based View and it has been so amazing . So i will explain some of the import Class Based View.

Generally in django we have the Function Based View and Class Based View, Function Based View are written by the developer. They have to write the code from scratch while Class Based View are generic View. The are ready made view. The important function of class Based view is to prevent re-writing of codes that already exists in Django. I will explain some of the Class Based View here . And i will also explain by creating a library project for further explanation.

After creating your virtual environment you can check my article on that here We will start by creating the models for the library

Screenshot (85).png

I created a library model with the fields(name, category and date). The last two lines in the models basically override the model default name in the admin. It gives it the name of the library.

Also make sure you register the model in the admins.py file

from library.models import Library
admin.site.register(Library)

Make sure you also add the app you created in the list of installed app in settings.py file

INSTALLED_APPS = [
    "django.contrib.staticfiles",
    'library'
]

Then make migrations

python manage.py makemigrations

And migrate

python manage.py migrate

Also include you app in the project urls

from django.urls import path, include
urlpatterns= [
  path(' ', include('library.urls')
]

Screenshot (86).png So let's get started with the view...

  • ListView: Django ListView is use to present/display a list of objects. ListView is use to get object from the database and it can also be paginated(To number the page).
from django.views.generic import ListView
from library.models import Library

class LibraryListView(ListView):
    model = Library
    template_name = 'library_list.html'
     query_set = Library.objects.ordered_by('date')

From the code above i imported the listView from the generic view I also imported the model we created.

Class Based view basically is a way to write a very simple code, all i did was just to name the models and that is the library, I also had to specify the template_name .

(NOTE: in a case where you did not provide the template_name, django will automatically name the template itself which will be in the format of the model_viewtype.html i.e in this case, the template_name will be library_list.html)

The last line in the code is about getting the model. i added the queryset because i want it in the order of the date.

Screenshot (87).png

  • TemplateView : Basically as the name suggest is use to render information and some context on the HTML page. It should not be use to perform any POST information but can be use to render context.
from django.views.generic import TemplateView
class LibraryTemplateView(TemplateView):
      template_name = "library_template.html"
      extra_context = {'library_category": "Javascript"}

Screenshot (88).png

  • DetailView: The detail view is used to return the detail of each data from the database.

    The major difference between the ListView and the DetailView is that the ListView returns the data on a single page but the DetailView returns the information of a particular data on a page. DetailView basically shows more about a particular data on the page.

from django.views.generic import DetailView
from library.models import Library

class LibraryDetailView(DetailView):
    model = Detailview
    template_name = 'library_detail.html'

Screenshot (89).png

One of the important thing about the detail view is how to set the urls. Because we are showing the detail of each data, it needs the a primary key or id or even slug for each data.

in the urls.py
from django.urls import path
from library.views import LibraryDetailView
urlpattern = [
  path('library_detail/<str:pk>', LibraryDetailView.as_view(), name="library_detail")
]

Screenshot (90).png

  • CreateView - The CreateView is used to add new data to the database.
from django.views.generic import CreateView
    from library.models import Library
      class LibraryCreateView(CreateView):
             model = Library
              fields = ("title",  "category")
              template_name = "library_create.html"

Screenshot (91).png

Note: Whenever you are using createView you have to set the get_absolute_url in the models.py file. It helps redirect after creating the data.

from django.urls import reverse
def get_absolute_url(self):
    returns reverse('library_list')

Screenshot (92).png

  • UpdateView - The UpdateView retrieves data from the database and then update it. The major diffrence between the UpdateView and the CreateView is that while the CreateView is adding new data to the database, the UpdateView is getting the data from the database and then updating it.
class LibraryUpdateView(UpdateView):
    template_name = 'library_create.html'
    model = Library
    fields = ("title", "category")

Screenshot (93).png

Just like the detail view, the update view should either use an id, pk or a slug in the urls.

Happy Learning