Michael_Maranan
Posted on January 12, 2022
Introduction
The Django CBV (Class Based Views) and FBV (Function Based Views) are the methods you can use to handle the MVT or the Model-View-Template workflow in a Django app. From their name itself what differentiates both of them.
Django FBV
Pros
1.Beginner friendly
It is easy to study and to code. If you look on someone's FBV source code, you can understand how the job was done under the hood just by reading the lines of their code. In terms of coding it, you can do it just like how you code any python projects.
2.Name it anything you want
You can name these functions anything you want unlike CBV functions. As long as it does the job
Cons
1.You need to do every piece of your code
Bit hassle to do. You need to code all the parts.
Example of Django FBV
def TaskList(request):
task = Task.objects.all()
context = {'task':task}
return render(request, 'base/tasks.html', context)
Django CBV
Pros
1.Have so many built-ins
Have so many built-ins to use instead of coding all of them unlike the FBV. Let's say you make a view for making tasks and saving it. Instead of getting its object values then save it by calling ".save()", you can simply use the built-in "CreateView", give the Model and fields, and it will automatically saves.
2.Built ins have cool features you're not expecting
Django CBV built-in like DeleteView already provides delete confirmation, all you need to do is to connect your template on your DeleteView and put some for about it.
3.Cleaner code
Since you can use many built-ins your code looks better and shorter.
Cons
1.Bit difficult to understand
Yes it is. CBV is a bit difficult compare to FBV especially when you're using built-ins and some part may look confusing.
2.Class functions should named based on calls
Like what I said earlier, you can't name its class functions base on what you want. You should base it in calls like POST, GET, etc.
class TaskList(ListView):
model = Task
template_name = 'base/tasks.html'
context_object_name = 'tasks'
Tip:
I you're a beginner, it's better if you use the FBV first and be comfortable with it before moving to CBV. A lot of Django built-ins for CBV was built for the simple tasks you do in FBV and if you hop in CBV without understanding why you need them and what it will do, you will get confuse.
Conclusion
None of them are better than another one. They have their own way in doing the job. There's something FBV can do that the CBV can't and also there's something CBV can while FBV can't. You should use what standards and kind of work suits the problem.
Posted on January 12, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.