DEV Community

Cover image for Django Class Views vs Function Views

Posted on

Django Class Views vs Function Views

Hello everyone and thank you for stopping by to see what it is I have to say. This is a topic I hear a lot about regarding to Django and I would just like to put my 2 cents in.

The DRY Concept

I'm starting off with this topic because it sets the tone for what I speak on next. A lot of you well developed developers know exactly what this means, but for those who don't... DRY - "Don't Repeat Yourself". Definition of insanity plays well with this concept if you'd ask me. I bring this topic up because its self explanatory. Don't repeat yourself when you are developing code if you can avoid it.

Class Based Views

At the core, class based views are simply python classes. Django does an amazing job shipping a variety of "template" class based views that have configured functionality that you can reuse as much as you want. When creating forms in Django, especially if it is a form that's being used multiple times, there's no reason to recreate something you can make once. This approach also helps with responding to different https requests with different class instances instead of using conditionals inside a single function based view.

Class Based Views Example
Alt Text

Function Based Views

I won't rule out function based based views too much. Some people are more comfortable with writing their own functions instead of writing classes essentially. I will say function views are easy to implement, but that's about all I can really say about it. The main disadvantage is if you are working on a large project then you will see a lot of repetitive code within your views.

Function Based Views Example
Alt Text


Now I know I can go deeper into this conversation with explaining pro's and con's using either method of creating your Django views, but I wanted to just point out the obvious that will be brought up in a conversation. As a junior developer I've always been told to keep things simple, but don't repeat yourself. When you keep things simple and create re-usable code you open up the door to having the flexibility to increase or decrease functionality.

I hope you guys enjoyed this quick snippet and I thank you for taking the time out to see what I have to say. Let me know if you guys agree or disagree in the comments and let's talk more about it or hit me up on twitter(@jcyber101 ). Cheers!

Discussion (1)

devparkk profile image
Dev Prakash

Brilliant !