What are Django class based views & should you use them?

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what are django class based views and do you need to be using them inside of your application so in this video what i want to do is answer that question talk about what class based views are along with some comparisons between a function based view and a class based view give you a full introduction and i also want to talk about an application that we're going to build out in a video after this that's actually going to utilize class based views so let's go ahead and show you that demo really quick so i'm just going to move my face out of here so we'll just move myself to the bottom right here let's put myself in a little circle and let's go ahead and check this out so this video is actually going to be based off of an article that i just wrote up on my website that's going to be linked in the video description i'll also link up the next video once that's finally out and that's going to be a to-do list application so let's go ahead and open that up and after this what i recommend you do is actually try building out this application here so what this is is a to-do list application it has login and register functionality so we can register an account we can log in and then add in some to-do items with some search functionality so this is all built-in using class-based view so you can apply what we learned in this video right after this so we can also modify items here so if we want to go ahead and cross an item off the list if we want to update an item we can go ahead and remove it so this is going to be the live example that you should test out so let's go ahead and go back to this article and what i'm going to do is zoom in i'll follow this but if you want to follow along with this video you can go ahead and pull this up and i'll try to zoom in as much as possible here so if you watch any of my tutorials you'll probably notice that i use function based views at least more of my beginner tutorials and i try to stay away from class-based views and there's a specific reason to that so a quick disclaimer i think class-based views are great i do use them in my own applications i just prefer function based views in tutorials because i want beginners to focus on the code a lot of people get caught up on the details of class-based views because they do have more of a learning curve so it takes a little bit more to figure out how they work what to do with them outside of maybe basic functionality like create update delete and read so i try to make sure to keep things simple so function-based views are a little bit more explicit you can understand exactly what's going on line by line all of our code is written out for us and that's why i stick to them so i just wanted to make that disclaimer and this isn't a comparison video in the sense of why i don't use class-based views and why i don't think they are good because i do think they are good so class-based views are very powerful and i think every single django beginner should learn them i think there is some context to where you should learn them or when you should start applying them but i think a good overall objective overview and when you should actually apply them would be why you actually are using django in the first place so if you're trying to apply for a job there's a good chance that any company that you apply for is going to be using class-based views so very early on if you're trying to just get a job after learning the basics i would recommend learning class-based views now if you're trying to enhance your application a little bit that's where class-based views come in but only after you understand the basics and can already apply them but if you're working on an application by yourself it's going to be you really have the full flexibility of doing everything the way that you want it if no one else sees your code so in that case you can stick to whatever you want so in this article i want to break down a few questions along with give you some examples and comparisons so some of the common questions that i get asked about class-based views are these so do class based views replace function based views should i use function based views and class-based views together and can i use them together and do or should i even learn class-based views and what are the benefits so we want to answer those so before we get started there are a lot of a lot of valuable resources for this and i want to link those up because with any video or any article or book that you read they're going to give you an overview and there are some articles or books that can go more in depth but i think the best resource once you start applying them something that you can use almost as your django bible for class-based views is the documentation itself along with the django source code on github and another website that i really like here so let's open these up so the first one is the django documentation use this this is where you can understand all the views these are built-in views you can see how they're constructed so if we go to the list view for example we can see all of the methods the view has some examples here and links to more information about this so we can go to any one of these methods see what it does a description about it and this is something that i still have to reference all the time a lot of people that know django very well still have to reference the documentation because there's just so much to learn so utilize that and i want to make sure that's linked up for you now the source code to django itself this is great because we can find any one of these views let's go ahead and find let's just do an edit view we'll go to edit here and let's just say we want to look for the update view so this is a built-in view let's say update view right here so we can see the view and we can see exactly how it's constructed so we can see that this is a class we have a mix in that goes in here which we'll cover and it inherits from the base update view so this doesn't tell us too much well we can go to any one of these views so let's actually zoom in here we can go to any one of these so i can go to the base update view that should link me up here so i can go here and this will take me to that part and i can see all the methods okay the base update view inherits from model form process form view and here are the methods to it so the reason why i'm saying this or why i'm linking that up is because to actually understand it you want to understand how these views are constructed so you want to look into that and get some more information about it and use that now the last example is actually not the documentation itself this is a website that separates the views into their general category and that separates it by authentication views general detail views edits and list views and we can go to any one of these views so we'll go to let's say our list view and just like the documentation it also gives us more information now i like this website a lot because i feel like the way they organized it with a description showing you all the i guess the parents or ancestors as they list it we can see everything that goes into this view along with all the attributes and methods so we can see that list view contains all of these attributes these are attributes that you'll need to reference later and then all of the methods so i just wanted to get that out of the way that's something that you should be referencing and let's go ahead and get started with this so what are class based views so in short class based views are simply django views written as python classes now at the end of the day every single view is still a function but this is encapsulated now inside of a class and we're able to utilize things like uh inheritance we're able to do multiple object inheritance we can also write more reusable code so this is listed on my article i should probably follow that so we can utilize inheritance we can also write reusable code and follow the dry method which stands for don't repeat yourself that means that we can extend a view we can reuse a lot of our code by just adding it in as a parent element so we'll see some examples of that in a minute here at the same time we have built-in methods and views eliminate a lot of re a lot of cases that we use over and over again so by creating a simple object listing out some data or getting a simple piece of information django already has built-in views for us that we can utilize so we're not having to repeat ourselves a lot here so there's a reason why we use things like frameworks in libraries because we don't want to have to write every single bit of code by ourselves and that's kind of what starts happening with function based views is that we're starting to write every bit of code when there are already methods that we can use so built-in class based views take care of that for us and eliminate redundancies and make for easier views here so we can also separate our code by http method so for example when you have a function based view any kind of method that you sent whether it's a post put get delete method any type of http request that you send to that view has to be processed inside of that individual view and that means that we're having to write conditional logic so if we send a post request we have to write a condition find it and then perform some behavior and django separates this for us by certain methods so we have our class but then that class has a list of functions and those are going to be a get function a post function and this is where we can write code in the individual functions rather than putting that all inside of one main function so we get to separate our code we'll check out some examples so django didn't always have class based views so i believe it was till 1.3 or maybe it's 1.9 up until that point django used to just have function based views and there were some ways of extending code django try to add in some basically added in some features to where we can extend our functions but functions are pretty limited and classes have a lot more flexibility and a lot more we can do with it because it's an entire object so it makes this a lot easier and that's where django introduced class-based views so they didn't always have it they added it to add in all of these features so let's take a look at an example of a function based view and then we'll compare it to a class based view so in this example we just have what would be like a website for an e-commerce website we have a product model let's say we have a bunch of products in our store so we have that model we have the render method and we create our simple view so we create a function we call it product list and we query all the products in the database let's say this is for our home page where we just want to display those we create the context dictionary we pass that in and i need to fix that that forward slash isn't supposed to be there so i'll get rid of that so we create our context dictionary and we return a template with the context dictionary so that's it that's a pretty simple view it could be written as a function doesn't take too much to do so inside of our urls.py file we just trigger that function after we import our views file and that's it so now the same view written as a class and this is going to be the example here is with uh a built-in class based view so the view that we're going to utilize is going to be the list view so this is a view built in with django and this view is in charge of returning back a query set and a template it's supposed to make for what we just did here a lot simpler now we can customize these views we'll get into that in a little bit but in this case we write a simple view now and instead of a function like we did up here we just write that as a class and i just call that product list and we inherit from list view so that means we have all the methods and attributes and the functionality that the list view has so we add that in here now list view at a bare minimum either needs a model or a query set so what this view is going to do is when we specify the model that's one of the attributes here it's going to go ahead and query all the products from that products table at least all the ones that we can query and it's going to return a template now we didn't specify a template name all that was taken care of under the hood it's sort of like magic and that's already done for us and we'll get into how to customize it and how that actually works here so inside of our urls.py file there is one thing that's going to be a little bit different here so in this case when we import our views this is not a function anymore because it's a class we have to trigger the as view method and we have this method because it inherits from list view which inherits from a set of views and as view is what needs to be called so our url resolver can find a function because it only takes in functions and not classes so as view will take in the http method and it's going to trigger the function that correlates to that so we'll also take a look at that in the documentation and see how it triggers that so that's the as view method it helps us trigger it as a function it finds a corresponding function and it just makes it happen so class based views uh the thing about these is it makes our code a little bit simpler but there's a lot of magic underneath the hood and this is where um it makes things simpler but can be very confusing for beginners so in this case this is where you it really helps to understand exactly what's going on so for our list view underneath the hood we query the database we passed in some data into our context dictionary and we returned a template we can't see how all that's done right here that's just kind of done magically so that's all because of its parent elements and that just kind of happens so before using class based views i would highly recommend you understand exactly how they work so if you understand exactly what's going underneath underneath the hood then you can actually modify them and customize them but once it gets into having to write your own custom logic this is where things can get a little bit confusing and this is where function based views really thrive in the beginning because as somebody that's just getting started maybe with programming in general and maybe not just django itself just the concept of views is something that you need to understand but if you start writing as class-based views you can maybe make it work but will you really understand what's going on so that's where it really helps to really study them and take your time so class based views i mentioned this earlier there's they separate our code by http methods so i just want to demonstrate that here and in this case what i'm going to do is send a post request to the same view so we have the same view we get the query set for all of our products we pass in the context dictionary and we render that template now in this case if we were to send a post request let's say that at the top of our page we just have a button that says add a product and we just create a product with some default settings we're not we're not actually sending post data we just want to create a product so in this case that condition is written into our view so we check the request method so we go ahead and write if request is if the request.method is post go ahead and perform this action if it's a get in that case by default to get request render out all of my products for me so all of that has to be written into the view now with the class based view in this case this is kind of a different example i guess we might write this differently in a real world example but just uh just to show you what's going on here there are already built-in methods so the post method is not a method that we're necessarily adding to this view it's something that's already there but in this case i want to override the method so in this case when we send a post request the view has a get request on the first request we can't see it but it triggers that so it sees a get request and it only triggers that function that's what that as view method does for us now if we send a post request we just say okay let's write in this method let's overwrite it let's create a product we're not having to write this condition and check it because we send a post request to one function and a get request to another which we can't see so that's how it separates it and it makes our code a lot easier and cleaner because we're not having to write that logic we're not having to write the logic inside of that function we're not having to check our conditions it just knows this is a post request this is a get request separate these two so that's something that i personally really like about class-based views so to summarize what class-based views are they're just a cleaner way of writing our views as classes and they add in a lot of functionality whether that's built in or the ability to build in our own functionality it makes our views a lot more powerful so do django class based views replace function based views so the answer to this is no it's just a different way of doing the same thing in theory you can you can still accomplish the same task but one is going to require you to write a little bit more code this is the example of like if you want to build out a website with just python and no framework you can still do it but why not utilize the power of what django gives us to give us all these methods and functionalities so that's what class-based views do they just give us a little bit more functionality or a lot more functionality so you can absolutely use them together that was one of the questions can you use a class based view and a function based view together yes in your in your views.py file you can write a class based view and a function based view right after and i still do that when i have a view that is simple and doesn't require a class-based view it's a simple action that i don't really need to make reusable i'll just use a function based view and then if i feel like a class base if you can make my code better i'll write that as a class so you can absolutely reuse them and yeah you can use them together and at the same time no they don't necessarily replace each other they're just different ways of doing that so should i be using class based views instead of function based views so the answer to this is going to be completely up to you so it's 100 up to you a lot of companies a lot of more corporate structures or organizations that are following best practices do use class-based views so it's something that's more common practice but it's going to be up to you and how you want to write your code so if you want to write clean and efficient code in theory class-based views are going to be the best option because they are more opinionated and they force you to do things the right way and they kind of clean things up for you but at the same time with this state or the problem with this statement is the fact that sometimes it you may make your code less efficient and it may be harder if you don't fully understand what's going on it can slow down your progress and i actually have an example of this so in 2018 i built out this application i've shared this story a lot where i built out this massive application and it upsell in it but for the first six months when i first started building it out i built it out i had a user base after six months but i started hearing about class-based views i knew what they were but i decided okay i'm advanced enough to start applying them after six months so i started changing all my views into class-based views thinking that that's the better thing to do i kind of blindly went into it after two weeks or so of studying because i just thought this is what needs to be done and i didn't really understand why i needed them i just did it because i wanted to that was a big rookie mistake and i ended up actually messing up my code i ended up adding a bunch of bugs and spent probably an extra month rewriting my code back into function based views and fixing things up and it only caused a lot more problems so the moral of this story is you shouldn't use them just because you think they're better you should use them because they can enhance something that you're trying to do but proceed with caution with them it probably wasn't i it was about a year before i actually really felt comfortable and i started slowly applying them into my application but this time it was because i saw the advantage in a specific part of my application now i still use a lot of function based views but i just utilized the full power of class-based views when when it made sense so let's start with the first class base view and this is going to be a class called view so this class right here is kind of like the granddaddy to all class based views all the built-in views inherit from this class based view and in theory we can create our own class based view by simply inheriting from this and this will give us all the the core functionality for a class based view so let's actually just pull up the source code i'm going to open this up i link this directly and it's going to link me to the django github repo and we can see that when we start here it's just a class right here and it doesn't inherit from anything else so this is the top top level of all the views here so we see the edit method we won't go into the details here we see that as view method which we called inside of our url parameters there inside of the url resolver we see let's see we see the setup method the dispatch method these are all methods you should read into and i thought that we would see the get and post requests i guess we have to write these in ourselves so this is the the base class right here and this is what we can utilize so i just wanted to show you that and where to find that and this is where all the other views inherit from so the list view the detail view that we'll get into later delete and update all these views at some point inherit from the view class so here's an example of us just using that built-in view now in theory we probably wouldn't want to do this we would want to use the built-in methods like the list view which we saw earlier but in this case let's say i want to write a class based view but i want to completely write it on my own i just want to make it a class but add in all the functionality on its own so we inherit from the view method and this is where you're seeing that separation of code and i probably should have used this example here but here we set the get request so when we first load this view let's say we're just trying to render out a template and some products here we query all the products we pass in the context dictionary and we return it so it's just like a function based view it's a function inside of our class now if we want to send a post request this is where we would write that same logic and we could just say create product send some form data and now that's all separated and at this point we're not utilizing the full power of it we're actually writing more code but this is how we can manually write our own class based view and that's going to be from that view method which is going to give us that core logic here so inside of the urls here we triggered that with the as view method right here we pass in the products and that's about it so keeping things dry now in this case we wrote more logic and this is where the built-in methods help so this is where we'll go back to that example and we'll start with the list view so the list view starts from that view class has a bunch of other mixins and and views and at the end of the day makes the same class right here the same view look like this so it simplifies it we're not repeating ourselves we're not having to repeat this right here because that's already done for us and it just simplifies that we pass in the product much cleaner doing it that way so what i want to do next is actually give you an example and this is going to be for that demo to do app which we'll do in a video after this once that's done i'll link it up here and i want to write a combination of views here and go into that now these aren't going to be so customized i just want to give you the functionality to first list out our products so we'll be able to list out all of our tasks right here we want to write in a single view to click on one of these products and view it then we want to be able to create an item so add in that functionality update an item so when we go to one of these we want to modify it and then the ability to delete an item so we'll write five different views to modify or five different views to perform five different actions so in our application this is what the views should look like here so we first have to import all of our views the first one is going to be our list view so from generic django.views we import the list view then we import the detail view from generic.detail and then from generic.edit we have create view update and delete view so we import all of our models in this case we have a model named task that's for our to-do list item these are different tasks on our list and we also have a reverse lazy function to redirect a user so in our tasks list we start with our list view we've done this before except for we're not doing products now we just list out all of our tasks so we don't have any search functionality or anything like that but we can just list those out now for our detail the detail view takes in the id from the url parameter or a slug field and i'll show you how to customize that and we simply inherit from detail view which we imported we pass in a model and when we trigger this the model or the view already knows how to get a product the product details how to render a template and pull up the information now for our task create view so the create view right here we import or we inherit from the create view with our task create class based view right here we specify the model we've seen that that's a consistent thing that we have to do and in this case the create view actually uses model forms so it has a model form already built into it so in this case we can use our own but and i'll show you how to do that but we are just going to specify the fields and when we render out our template we can just use the default form that it gives us and just like magic we have a template with a form with all the fields that we specified we could also specify all the fields here too then we also set up our success url and we want to redirect back to our tasks once a different or a certain task is created so that's our create view now for our update view it also uses a model form so it's very similar to our create view our update view right here we give it the model in this case it finds the specific the specific model by its id just like detail view does we specify the fields and we give it a redirect url and then delete view also gets a model by the id just like detail and update view and in this case we actually redirect a user after deleting it so it takes in a get request to render a template like a confirmation so if we go back here we can go to one of these let's go ahead and remove this it pulls up this delete page right here this confirmation we delete it and it redirects us so these are our five views and this is how we can use some of the built-in views and probably some of the most common views as far as class based views after or with along with authentication views so with these we import all of the views here we enter inside of our urls we import each view that we created so task list detail create update and delete and we pass all of those in with the as view method so pretty standard here we're just changing up how we how we use that inside of our urls and that's about it so these are created to make the basic functionality easier for us django already knows that creating listing out and deleting items are a very common practice something that people do a lot so they created views for us so to understand how class-based views work we want to understand how they are constructed so django class-based views are simply a collection of mixins and other views so there's a lot of inheriting going on and a combined set of mixing and views create every single view to give it its functionality so if you don't understand what a mixin is this isn't a django or a python thing this is uh used in many different languages a mixin is simply a class that is designed to provide a certain a certain level of functionality and it's supposed to do one specific thing so if we see that we do something over and over again we can create create a specific mixin and utilize that inside of a class and that'll give us a specific action that we can perform so it just extends our classes so that was my poor explanation of what a mixin is so we use mixins and classes to create a certain view so if we look at our list view let's start here we can see that our list view starts by inheriting from multiple object template response mixin which gives us some functionality and then it also inherits from the base list view so these two views give the list view its functionality so this is what creates the list view now these mixins and views also inherit from other mixins and views so if we go down here we can see that we inherit from one mix in directly or one mixin and one view directly so the first level but all together we have six different mix-ins and views and those are listed out right here so we have the base list view multiple object mix in content mix in that view class because every single view inherits from that view class that we referenced so to see how this actually works i actually drew up a diagram for each one of these main views so we can see our list view and these are the two first level views so these are these ones right here so the multiple object template response mix in inherits from template response base list view inherits from view multiple object mix-in and context mixin so this is where when i showed you that reference to that documentation this is where you should really consider using that because by going to those you can see exactly what this mix-in does right here and what this one does and see exactly what to do here and how this view is fully constructed so i just wanted to show you that diagram and explain how the inheritance works to create a specific view now i'm going to have a few examples like this for different views and each one of these will have different objects or different mixins and views that actually inherits from so we can actually override some of the default settings or i guess all of the default settings and in our task list or inside of our list view what we did before was we just had the model and that was it and it rendered out a specific set of items the weird thing is is where does the template come from we never specified a template just like we do in a function we actually specify exactly where we want to find this template uh where do we how can we order objects how does it know how to name the objects in the template and so on so a few of these that we can customize are the attributes here so this is where i recommend looking at this link right here so i'll pull this up and then i'll go into these so in here we can see a list of attributes so the one that we're going to override is going to be the template name so by default the list view looks for a template with the the prefix of the model name so in this case our model name was task so the prefix is the model name and the suffix is underscore list.html so if we don't specify it django by default or the listview by default is going to look for this template tasklist.html now if our model was product it would look for a template called product underscore h or product underscore list.html wow blinked out there so we can override that let's say we just wanted to call that tasks so we can just specify the template name and there we go we simply override that now in the template how do we reference the actual objects how do we reference that query set well by default that is called object list so if we wanted to loop through a list of products we would have to do something like for product inside or for product in object list go ahead and do this render out these products here well i don't like that name because it's not really user friendly if i'm working with somebody they might not know what that is so let's say i wanted to rename that to products or in this case tasks so i wanted to do four tasks inside of tasks in this case i can just say context object name set that to task and now it's not object list but it's tasks or we could call that tasks list so that's an example of overriding a few things we also have built-in pagination and ordering all we have to do is specify those and like magic all of that's done for us so i linked up all of the attributes or all of the the documentation and source code for the specific view so this is for list view if we go to detail view i already kind of covered what this is in this case we see the mixin and the view that it inherits from and the detail view by default here is all the mix-ins and views here is the overall flow for the detail view and this is what comprises or builds the detail view for us so overriding the default values the template name by default it looks for the prefix of the model name so it looks for task and then it looks for underscore detail.html so if i want to customize that i just go ahead and set the template name we've done this the context object name by default is just going to be called object in the template so we can override that and i want to call it just task so i want to reference it by that instead of just object now detail view also looks for the id inside of the url and by default this should be called pk so if i want to change that i can actually set the pk underscore url keyword argument and we'll just call that custom pk for whatever reason some people might want to call that id but in this case i like to leave it but this is how we can override that and all of the links to detail view so then we just have our create view we see all of the inheritance there's a little bit more because it requires a little bit more functionality we also have oh and by the way so the prefix to this is going to be the model name and then the suffix is going to be underscore form.html so it's the same for our update view too it also looks for the same template now in this case remember when we specified our fields so in this example we added in the title description so these are all the fields to that default model form so let's say we wanted to create our own model form so this case we can actually build out our own model form we take out the fields attribute and in this case we just set the form class and we pass in the model form that we want to use so that's how we can override that method right there so form class just overrides it and detail view in this case the temp or the template prefix and suffix the template prefix is going to be task the suffix is going to be underscore confirm underscore delete.html so we also have the primary key url keyword arguments and that's about it so those are those five views i wanted to show you how to customize those and maybe how you can find the detailed information about those now let's talk about more django built-in view so django separates views into different categories we have generic base views generic display views editing views generic date views which i don't use too often and then authentication views so it separates things into these categories and we actually have these listed out so if we look at authentication views we see the login view log out view password reset views right here i really like using these even when i use function based views i like to use the password reset views because that's a that's a lot of functionality would have to build in by ourselves so i really like just using the built-in methods so we have the authentication views the base views right here which is the template view that view class and redirect view and then list view detail edit and all of our update views so create delete form view and update view and we won't go into detail view so take the time to study the links that i provided an article can only give you so much i'd recommend practicing and studying the views and really looking into it so the conclusion here is that django class-based views are very powerful but they do take some time to learn so for me it took me almost a year to really start utilizing the power but i was also in i was also in in the field right away so i really didn't have the time to study them it could be it'll probably take you a lot faster than that but the point is that you should understand what you're doing before you start applying them or at least how to customize them and how to override certain methods so one thing about this is i feel like the more you stick to django the more likely you are to the more likely you are to use class based views once you start trying them out you'll really start seeing what you're missing and the power in them so i hope this video helps definitely check out the article and look forward to the to-do list application that uses the class-based views
Info
Channel: Dennis Ivy
Views: 19,480
Rating: 4.961853 out of 5
Keywords: Programming, Software Developer, Dennis Ivy, Dennis Ivanov
Id: RE0HlKch_3U
Channel Id: undefined
Length: 36min 19sec (2179 seconds)
Published: Thu Mar 11 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.