Open In App

Class Based vs Function Based Views – Which One is Better to Use in Django?

Last Updated : 25 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Django…We all know the popularity of this python framework all over the world. This framework has made life easier for developers. It has become easier for developers to build a full-fledged web application in Django. If you’re an experienced Django developer then surely you might have been aware of the flow of the project. How things run in the boilerplate of Django and how data gets rendered to the user. 

Class-Based-vs-Function-Based-Views

Django works on the MVT concept we mainly work on two types of views in it… class-based views and function-based views. If you’re new to the Django framework then surely you might have been using FBVs (Function Based Views). 

Initially, Django started with the Function Based Views but later Django added the concept of class-based views to avoid the redundancy of code in the boilerplate. It is a debate among developers which one is better to use in Django… class-based views or function-based views? Today in this blog we are going to discuss this topic in-depth to get to know the pros and cons of both of the views. 

You can accomplish your task using both of them. Some tasks can be best implemented using CBVs and some of them can be implemented in FBVs. Django views have mainly three requirements…

  • They are callable. You can write the views either using function-based or class-based. While using CBVs you inherit the method as_view() that uses the dispatch() method to call the method that is appropriate depending on the HTTP verb (get, post), etc.
  • As a first positional argument, Django views should accept HttpRequest.
  • It should return the HttpResponse object, or it should raise an exception. 

Now let’s compare both of the views and see the pros and cons of both of them.

1. Function-Based Views

Function-based views are good for beginners. It is very easy to understand in comparison to class-based views. Initially when you want to focus on core fundamentals, using the function-based views gives the advantage to understand it. Let’s discuss some pros and cons of it. 

Pros:

  • Easy to read, understand and implement.
  • Explicit code flow
  • Straightforward usage of decorators.
  • Good for the specialized functionality.

Cons:

  • Code redundancy and hard to extend
  • Conditional branching will be used to handle HTTP methods.

As we have discussed function-based views are easy to understand but due to the code redundancy in a large Django project, you will find similar kinds of functions in the views. You will find a similar kind of code is repeated unnecessarily. 

Here is an example of a function-based view…

Python
def example_create_view(request, pk):
  template_name = 'form.html'
  form_class = FormExample

  form = form_class

  if request.method == 'POST':
    form = form_class(request.POST)
    if form.is_valid():
      form.save()
      return HttpResponseRedirect(reverse('list-view'))

  return render(request, template_name, {'form': form})

All the above cons of FBVs you won’t find in class-based views. You won’t have to write the same code over and over in your boilerplate. 

2. Class-Based Views

Class-based views are the alternatives of function-based views. It is implemented in the projects as Python objects instead of functions. Class-based views don’t replace function-based views, but they do have certain advantages over function-based views. Class-based views take care of basic functionalities such as deleting an item or add an item. 

Using the class-based view is not easy if you’re a beginner. You will have to go through the documentation, and you will have to study it properly. Once you understand the function-based view in Django and your concepts are clear, you can move to the class-based views. Let’s discuss the class-based views in detail.

Pros

  • The most significant advantage of the class-based view is inheritance.  In the class-based view, you can inherit another class, and it can be modified for the different use cases.
  • It helps you in following the DRY principle. You won’t have to write the same code over and over in your boilerplate. Code reusability is possible in class-based views.
  • You can extend class-based views, and you can add more functionalities using Mixins.
  • Another advantage of using a class-based view is code structuring. In class-based views, you can use different class instance methods (instead of conditional branching statements inside function-based views) to generate different HTTP requests.
  • Built-in generic class-based views.

Cons

  • Complex to implement and harder to read
  • Implicit code flow.
  • Extra import or method override required in view decorators.

Below is an example of a class-based view…

Python
class MyCreateView(View):
  template_name = 'form.html'
  form_class = MyForm

  def get(self, request, *args, **kwargs):
    form = self.form_class
    return render(request, template_name, {'form': form})

  def post(self, request, *args, **kwargs):
    form = self.form_class(request.POST)
    if form.is_valid():
      form.save()
      return HttpResonseRedirect(reverse('list-view'))
    else:
      return render(request, self.template_name, {'form': form})

We have a little abstraction and method as_view() is calling the dispatch() to determine which class method needs to be executed, depending on the HTTP request. as_view() let you override the class attributes in your URLs confs. You can do something like the below…

Python
urlpatterns = [
    url(r'^new/$', MyCreateView.as_view(), name='original-create-view')
    url(r'^new_two/$', MyCreateView.as_view(template_name='other_form.html',
                    form_class='MyOtherForm'), name='modified-create-view')
  ]

Once you start using the Django generic class-based views, you will be able to over-write the helper method like get_form_class and get_template_names. You can insert the additional logic at these points instead of just overriding the class attribute. 

One of the good examples of it is…ModelFormMixin. form_valid method is overridden. With the updated value stored in self.object() form_valid method is overridden. 

3. Django Generic Class-Based View

Creating a new object, form handling, list views, pagination, archive views all these things are the common use cases in a Web application. It comes in Django core, you can implement them from the module django.views.generic. Generic class-based views are a great choice to perform all these tasks. It speeds up the development process. 

Django provides a set of views, mixins, and generic class-based views. Taking the advantage of it you can solve the most common tasks in web development. 

The main goal is not to reduce the boilerplate. It saves you from writing the same code again and again. Modify MyCreateView to inherit from django.views.generic.CreateView. 

Python
from django.views.generic import CreateView 
class MyCreateView(CreateView):
    model = MyModel  
    form_class = MyForm


You might be thinking that where all the code disappears. The answer is that it’s all in django.views.generic.CreateView. You get a lot of functionality and shortcuts when you inherit from CreateView. You also buy into a sort of ‘convention over configuration.’ style arrangement. Let’s discuss few more details…

By default template should reside in /<modelname>/<modelname>_form.html. You can change it by setting the class attribute template_name and template_name_suffix. 

  • We also need to declare the model and form_class attributes. Methods you inherit from CreateView rely on them.
  • You will have to declare success_url as a class attribute on the view or you will have to specify get_absolute_url() in the model. This is important for the view in your boilerplate else the view won’t know where to redirect to following a successful form submission.
  • Define the fields in your form or specify the fields class attribute on the view. Here in this example, you can choose to do the latter.

Look at the example given below to check how it will look like. 

Python
from django import forms
from . models import MyModel 
class MyModelForm(forms.ModelForm):
  class Meta:
    model = MyModel
    fields = ['name', 'description']

Conclusion

It is still a debate among developers that which one is good to use. Class-based views or function-based views? We have discussed the pros and cons for both of them but it totally depends on the context and the needs. We have mentioned that class-based views don’t replace function-based views. In some cases, function-based views are better and in some cases, class-based views are better. 

In the implementation of the list view, you can get it working by subclassing the ListView and overriding the attributes. In a scenario where you need to perform the more complex operation, handling multiple forms at once, a function-based view will be a better choice for you. 



Next Article

Similar Reads

Practice Tags :
three90RightbarBannerImg
  翻译: