Django Rest Framework Series - Viewsets and Routers with React Front-end Example - Part-4

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello and welcome back to the django drf and react series so far in this series we built a simple restful api with django and also the react front end in the second tutorial we looked at permissions and how we could apply them and then in the last tutorial we looked at token-based authentication so we pretty much built a system from the ground using token-based authentication and what we ended up with is a whole system where we could register log in and log out hasn't been completely fleshed out here you can see this is just for for us to indicate that we've got these facilities here and you can see that these posts here this is a simple blog application these posts here are being generated from our django restful api so the back end of this tutorial we're going to go back into react and django we're going to apply what we're going to be talking about today to build a new feature here so obviously we can look at all these different posts here but what we want to do now is drill down to these posts and look at them individually so that's what we're ultimately going to build in this tutorial but the main focus of this tutorial is going to be view sets and routers so now we've got the drf project off the ground we can now focus on further feature development as well as theories best practices code patterns and techniques the topic of this tutorial some might consider is on the advanced side of things but i strongly believe that you can develop more effectively knowing what is possible rather than knowing how to code out something because more often than not there's loads of tutorials online to help you write code but very little telling you what is possible so this is one of those and hopefully you can then explore the topic further at the end of this tutorial but hopefully i'll just give you a grounding and an underpinning knowledge for you to apply to your project if you want to and then research further so the flow of this tutorial we're going to go over what view sets are and actually apply them well provide you some examples of course and then we'll have a look at routers so these two technologies really come in hand in hand they work together so once we've done that provided some examples we'll then move slowly forward to where we want to be and that's building a single post or detail view so that we can create an api endpoint that we can point at that's going to retrieve an individual post that we request in our react front end application so the question to begin with then is why would i want to use view sets or routers so obviously you probably got no idea what that is at the moment so let's just put a picture in your mind the problem so as your project scales increasingly you get a large amount of views so this is probably typical in any django project as things scale up but in addition to that you also scale up the end points because here utilizing restful apis typically every view has an endpoint or potentially multiple endpoints again that's not too dissimilar to developing a normal django application where you have views and your urls but in addition to that we can also see there's a lot of repetition of code in the views so you've probably seen this already for example we've only written two views here but you can see there's repetition here for example we're using the same query set although we're using a different manager here we're using the same query set so could we kind of remove that slim that down now of course that's just one line of code there but when you start scaling this up in your project that becomes a lot more writing a lot more sorry code coding that you need to develop so ideally you want to follow the dry principles here of not repeating yourself so these technologies that we're going to introduce the view sets and routers that's going to help us overcome some of these problems and as you probably already started to find out managing multiple endpoints or urls can become difficult to maintain sometimes you need to have them in the right order for example for them to work properly and so on so again view sets and routers particularly routers in this case is going to help us overcome and alleviate some of those problems again particularly of larger projects so first of all we're going to have a look at view sets and then we're feeding routers so to get an idea of how they work together so a view set is considered a a way or a method to speed up api development by basically having to write less code that's essentially what's happening here we have to be less explicit because django in the background has the code pre-written for us in for example other classes and mixins in the background so because we're utilizing this similar to class-based views we have this level of of abstraction so there's a lot of things going on in the background that unless we really drill down into and read through we won't truly know what's going on and that can make it difficult for some to develop with view sets because you have to have an understanding what's happening in the background i kind of take a different opinion here and i think that it makes it easier for you to write code if you don't know what's happening in the background all you need to know is what you can do and then just leave the background code to do what it does at least in some situations so what's happening here then with the view set is we can bunch up classes so essentially we can replace multiple views with a single view set so what we're doing with view sets is we're basically just slimming down code we're trying to match similar classes and then we're going to put them together we still have the function of both of those or more than one or two sorry of those classes that we bunch together so we still got all the functionality that they provide those individual classes but it just allows us to write less code we can start to strip code that's similar between those classes and we put these classes together in the view set and just makes it easier and like we have at the top here it can speed up development so like i said repeated logic can be combined so ultimately we're writing less code and it promotes dry don't repeat yourself so let's have a look at actually applying this to our project so you can download the code in the description we're in the blog api here application so this is our django backend so here you can see that we've got in our views we've got two views one view that that displays all the data and we have one view here that deals with the individual items so display all posts and just display one post depending on the criteria that we provide so let's just go into the core and our settings let's just turn off the authentication so that we can utilize the interface so we've got the server on so let's go into our front end here so here we're using the api view so you can see here that this is our api endpoint we've got all of the items from a database there's only two items and then i can drill down based upon id into the individual posts okay so that was two different posts there id number two so that's how it matches up so let's see how we can use viewpoints to cut out some of this code or reduce some of this code so first of all we need to actually import view sets so let's go ahead and do that rest framework and what we're going to do is we're just going to remove these classes for now and we're going to recreate them but in a view set so first of all we're going to need a new class then and we're going to apply view sets dot view set so i'm going to show you two options the first is the view set dot view set so essentially what's happening here this is a simple type of class based view so this is going to allow us to have some abstraction in the background it's going to be connected to everything that we want to potentially utilize to list or create files uh or posts or in this case in the background so here's the level of a bit of abstraction that it's providing but what this does the view set is it provides us all the tools for us to do what we need to do and now we can just select what tools that we want to use so this is very much a a top down approach where we we are just given everything and then we can prune and change and delete or remove the items that we don't need so that probably sounds a little bit abstract so let's have a look at what i mean so we've got our view set here now previously we needed the query set we needed the serializer and we did have permission classes so we can still continue using permission classes in our view set that is just something we can that we can just take out and place there so that's something we can learn about the view set we can just use the normal permission classes as per normal what we can also do is define the query set and we only need to do this once and we can do it right at the top here and now that can be utilized for all the other functions that we create so now it's up to us to actually then build in what it is that we need the functionality that we need so what we have here in green is basically all the different options so for example if i wanted to the first class here this just basically lists out all the items so this is this is just a list so i look at the tools i've got available here i'm just saying well i want to use list so now i'm just going to take a list and then create a new function here so we just start off with the list we call it list so we have self and request so we take that all in and now i just need to define two things first of all the serializer that we're going to use and that's pretty much it because you can see up here we've got the query set so let's go ahead and just paste that in so we've got two items here like i've said the serializer and the return okay notice that we need to include response so we just need to import that in from the rest framework there we go so that's from the rest framework response response so we return the response here which is basically the data from the serialized class but remember it comes from the query set here so we query the data we run it through the serializer and then we respond back so that's a simple way of creating a list or or to return a list utilizing view set so what's important here to understand when you're using view set are these functions here because this is all the power so that's obviously listing items so we can do that now if we wanted to create an item then obviously we would use this now remember to create an item remember from our api we send a post request so the view set doesn't necessarily work with get and post but the meaningful action is translated into one of these functions here so if i sent across a post request obviously i would be asking to create something so therefore i'd build this create function which deals with all that functionality so retrieve that's essentially saying retrieve something from the database normally a single item so if i wanted to return an individual item similar to what i've performed here previously where we've got the individual post and obviously i'm going to use this right here so let's go ahead and do exactly that so the next up i just want to make a simple function here and let's just remove that so you can see here i'm using retrieve so i then go ahead and utilize post equals get object or 404 so what i'm doing here is i'm getting an individual object of course from my database so what database am i using well i'm just using this database up here still so you can see here that i've i've asked for this pk equals pk the primary key so essentially what that is there is when i type in this number here to get the individual post that essentially becomes the primary key so that gets passed across to my view here then into the retrieve i then can capture that through the request and then you can see that i can then utilize it to get a single object from the database i then of course run it through the serializer and then i then send a response which is obviously the data return back from the serializer there we go so there we go we now have two functions utilizing viewset so at the moment when we try this out it won't work okay because there's a conflict now we created urls for this now the urls or the existing urls won't work with this implementation so this is where router comes in so whereas before we we had to actually define all the routes for our views now we have routers or the possibility of automatically generating url patterns for the views that we have so the routes that will be created for each and every view set will include the possibility for us to automatically create retrieve update and destroy so when the route router creates a a route for our view it automatically sets up all of the routes that we might need to create retrieve update and destroy so basically just an automated way of creating urls but instead of creating individual ones it just creates everything that you could possibly want or need for that particular view of course this is can be overwritten and we can apply individual roots if we want to but this is a handy tool potentially you might want to utilize to automatically create url patterns so this probably looks familiar we have our url patterns for both of the different views that we had so what we can do now is just remove those because we're not going to use those in the view you see that we're only using post list now to define both of these actions so we're not going to need post detail so that slims it down there so now what we have we can remove the now we'll keep that for now so now what we can do is bring in our router so we don't need paths anymore we just need to bring in our views and then we just need to bring in the router so from the rest framework again we're using routers so there's no installation here we just need to bring in the tools from the rest framework and that's the default router so we then bring in the default router into a variable here so we can access it and now we're going to make essentially a new url which is going to be this so we've got here router.register to register a new route and you can see here this is just the default route as per normal let me just bring back the old url so you can see them so here we have this view right here this is just the root directory so the api and nothing the root directory for that you can see we're using post list again and this time we're just kind of a base name instead of name we're just going to call it user but we could change that if you want to okay so that's what we need to do there and then finally we say actually we tell django that we're not using url patterns anymore and the router will now take over the url patterns so that's why we have that last piece of code right there so we can actually i just want to change this to patch to make it a little bit more relevant so that should be it well let's go into the front end now and have a look so let's start off with our base there we go so you can see that we're returning in our route both of the items are in the database and we should now be able to also select by id the individual items there we go id number one and then number two there we go id number two so just to summarize the most important aspect there of you set is in our react application like i previously mentioned we might be posting information or we might be requesting or sending a get request now that's familiar if you've seen the other tutorials remember we use post and get to get data from our restful api now view set is going to translate this into create list delete etc so that's how things are kind of being moved across in the translation between post and what then is actually performed and the functions that we create in the view set so that's pretty much the the big take-home thing here to kind of learn and remember if we want to use view sets and just explicitly almost create our views but also with the possibility of bringing in an other code if we want to so here the the key main element here in terms of dry don't repeat yourself was we were actually then bringing in the query set and only applying it sorry or assigning it once so the question is now can we also bring in a serializer class without having to define it here well you can see in actual fact that that isn't necessarily going to be possible um because of how we're utilizing or how we're serializing we're still utilizing the same post serializer and so that's not always going to be possible so we're not going to move across and provide you an example of all of these but as we go through this series there'll be no doubt opportunities for us to just revisit this and create some more functions here so let's just focus on the router for a couple of seconds here so you can see that the router is automatically providing the facility to not only supply this route or this endpoint but also the end point for the individual instance so let's just see what's happening in the background if i just uh do something here you can see that these are all the routes that are available so the router is automatically building these routes here anything with api on so i mentioned that the router automatically creates routes so that it can potentially handle create retrieve updates destroy etc so that's pretty much what it's done here we're not going to drill down into these individual items here now it's worth checking out the tutorial that we built on the topic of regular expressions because that's going to help you understand what it is that you're looking at in these different paths here so what all these symbols mean etc so definitely have a look at that tutorial if you want to understand that a little bit more but we're not going to go into that right now all we need to understand here is that the router is going to create automatic pass for us to us for us to be able to perform multiple operations that just does that automatically and important to also understand like i mentioned is that you can see that it's capturing the item as this pk here so let's just go back into this again in our api so when i type in 1 here that's being passed over to our view as pk and that's going to be important to remember in the next example so now we're going to take a look at model view set which is the secondary item that we can utilize up here so instead of view set we can now use to lies model view set so let's just remove this or just uh line comment this out let's uh recreate this again but utilizing view set model view set so the model view set provides us a much more powerful set of tools i say powerful and what i mean by that is it just abstracts abstracts a little bit more for us so that we need to do even less so this is all the code originally that we've written for these two views and this was um what we ended up with utilizing view sets now we're going to do exactly the same thing but with the model view set so here we go there we go that's it so that's all you need to write so you've got the permission class and the serializer class we're probably going to need a query set in actual fact so let's just bring in a query set there we go so that's it so let's have a look to see if that works so let's go to our api home there we go that seems to be working and then the individual posts number one id number one and then number two so this takes us to another level of abstraction behind the scenes the model view set is important different mix-ins in actual fact it inherits from the generic api view and you can read about the generic api view in the manual or the documentation and that gives you an idea of what tools it has available now if you just hover over it actually tells you here it's a view set that provides a default create retrieve update partial update destroy and list so it has all the functionality that we need if we tie it up or connect it up to our router you can see that our router already has all the tools that it needs and all we need to do i'm repeating myself here again apologies all we need to do is serialize and provide the query set so hopefully you can see what's happening there again we can utilize permission classes like before that isn't a problem so let's now expand this so where something like that becomes a problem is once you start customizing or wanting something different from the default here so you can see potentially here what's happening is that django has pre-written code already and that's just dealing with everything that we need so if we want to overwrite this then we can do so if you followed or looked at any of the class-based views tutorials sorry for the promotion again um we started to go through this idea of that these classes here inherit other classes of a code and by doing so inherits all the attributes and functions within those classes and those classes may then inherit from other classes and so on and so on and we have also something called mix-ins which also can be inherited in to create this multiple inheritance and essentially this is a map of code that's all connected together that we can utilize and it's funneled down into this model view set and then we can access some of those parameters so let's have a look at how we can extend this there's probably two things that you want to extend here one is to utilize a different query set so we can define a custom query set so why you might want to do that is because maybe you've utilized a query set for maybe multiple items here or maybe remember that we might want to perform different actions based upon what the user has requested so we might want to use different query sets depending on the type of request that we receive from the user so similar here we've got list retrieve list blah blah so all this is still integrated here we just need to be able to access it so let's just define a custom query set so we can do that through get query set so this is how we define a custom query set so we're going to overwrite the get query set and again this feature or this functionality is somewhere embedded in a inherited view or class that this model viewing set is connected to so here you can see we're just going to use post object or again so nothing's changed here but just to give you example what's going on there so we've got two items here get query set which is get the query set so get the actual data we want to work with and then we also have get object so what we're actually doing now is we're going to build the functionality so that we can in the browser type in for example category for example django and that would take us to all the posts that we have in django so we can build categories but sorry in actual fact what we're going to build here is an example of when you actually select a post item what's going to happen is we can put the id in the top here and then it's going to show that individual item so that's what we're going to simulate and we're going to build but what we probably want to do in actual fact is type in for example a slug name in order to get to the actual post that's a little bit more seo friendly than just utilizing a number for example so let's just go one step further and we're now going to just utilize a slug so we need to add a slug field in the model shortly so that we can build some slugs like this so that we can navigate to individual posts so now let's build out that facility to get this working so what we're going to need to do is to overwrite the get object so we want to define what we mean by getting a single object so let's do that first first of all we're going to take in the primary key so remember we've got these um arguments here that we can take in so what's happening here in the browser we're typing in for example number two that's a an argument which we can we can capture so we're gonna capture that through the kw arguments here and you can then go ahead and save that in a new variable here called item so let's just uh move that across so here we go we've captured it now remember it was called pk so back in the browser here remember we were sending across um it was referenced to as pk so that's why we're using utilizing pk here so we're getting that item whatever someone's typed in we're putting it into this variable called item and now what we need to do is i'll just run a query on an object so we just need to return and then use the get object or 404 so that's going to get a single object from the data we're using the post model and then we're saying that title equals item remember the item is the number that we typed in but we're not going to use numbers remember we're going to be utilizing letters now how that is possible if you're wondering because it says pk for primary key so you'll be expecting possibly only numbers if you go back in it tells you here the format and that's a to z or zero to nine so that is why we can now type into this primary key holder here letters and numbers and capture them so we've got that coming back now and now we can use the title to access the individual post right so that should do it i think so we just returned the individual post good so what's going to happen here then is that when we go to the root directory this is just going to be fired off that's what's going to happen because we don't have an object to run this so that's why we get all the items when we type in a post name into the url this is going to be fired off because we've got some data in order for this to be processed so let's go ahead now and test so we can see that if we go to the root directory we still access everything now let's just take this title it's called new so this one here is called new one so let's just take new and there we go so we now have the new item now you can imagine what we now have here is an endpoint that we can now use in react to point to this particular police piece of data so now what we've got is our individual view so all we need to do now is go into react and then create a new page and then point axis to request this item and now we have an individual single post page so before we start developing back in react we're just going to turn everything back on from our server so let's just go back into the settings of django so that's the core settings and then we're just going to turn on the we're going to turn on the authentication class so we do that um okay so we've got the authentication back now so let's go back into our application here and it looks like we've got a problem so let's just see if we can log in again this would be an issue so it looks like the network's down at the moment so let's just find out why that is so the problem here was those two settings first of all we just need to reconfigure our url paths because we're utilizing uh roots or the router and also the path here i've moved down to the bottom there's just some configuration conflict here with some of the permissions and it was expecting us to be authenticated with jwt before we actually sign in which is obviously impossible because we need to sign in first to get our tokens so i put the tokens at the top here in the url paths in the core there secondly what you can also do in the settings and the core settings just change your origins so you can add some more origins if you want to i was using 127 colon 3000 but in actual fact i want to utilize localhost or at least that's the only available origin that will be able to access this system if you're wondering at this point actually um well if i have to specify who can connect to my rest api well wouldn't i have to specify everyone in the world of course you can blanket this out so that anyone can access it and so on so that's out of the scope of this tutorial but just in case you were wondering that so let's go back into react here so what we're going to do this can be a two-step process we're just going to go over the first step so i mentioned that we're going to type something in here and that will then take you to the individual post or at least when we click here the url will now say new because that's called new and then that would take us to the individual post so we're not going to do that just yet what we're going to do is we're going to connect this up so when we click on the item it takes us to that single page so back in react here we're going to open up the components we're just going to create a new component we're just going to call this file single dot js so that's going to show a single item so now we've made our new component let's just go back into django there's a few things that we need to do to get this working now if you remember in the blog we've made a model the model included the slug so what's happening here is that when we make a new item or when we make a new post we're generating a slug and that's a a usable piece of text that can be utilized in the url in addition to that we need to also bring it into our serializers because if you remember we didn't actually include it originally in a serializer so we need to add the slug there so we also return that data to react that was a very bad description there of a slug so if we go into the posts here i've just changed them i've just added some more posts you can see that we've got a title here and what the log does it takes the title and makes it into a url friendly string so this can be utilized in the url now let's just head back into the views where we were so the blog api views and i've changed title to slug because what i want to do is i want to select the item based upon the slug that we pass over and not the title that makes sense shortly once we start coding in react so now we have our new component which is the single so what we're going to do now is go into the index and you can see that i've created a new root here for the post so we've got slug component single so we can utilize that so we can take out this slug and we can then utilize that within our logic to then send off an axis request for that particular slug and obviously that slug here that we're talking about that's in the url that's going to be passed over to django and we're then going to run a query on the database and look for the slug that matches the particular post and then return that individual post so now that's in place we can then also just make sure that you import the single in at the top here so now let's go into the single so i've already recreate i've already created this so i can just run through this for you so you can see that we've got react again we've imported excess axia sorry and then we're going to be utilizing use params and i'll show you that in a second from the router dom this is just the material ui items as per normal like in the previous tutorials we've got the user styles here just some overwrite styles for material ui overriding styles and we're not actually using those i just put those in place there so you can see here that use params so what this is is it allows us to extract from the url the in this case the parameter slug so if we go back into the index we created this additional component here and that's the item that we want to capture so what we're doing here in the single is we're just capturing that item we're calling it slug so we're making a new variable called slug and we're storing that inside of that and then we go ahead and we've created our state now i'm not too sure why i called it hits um i'm not too sure so just change that so we're going to store the posts so here we go we create a an axios request get and then we draw in or we add in the slug so what we're going to do is we're going to send across the slug item so that's the component at the top in the url so now we've got that that's what gets sent across so if we go back into django you can see we collect that item and then we run it against the database so we've collected it from the url from from the data sorry that we've the request sorry that we sent across and we put it into item and then we run the database query so back in here then we collect the data we uh collect the data and then we put it then in our state so now we're storing it right here in our state the data that gets returned so down here we've got our container and then we've got some other elements here ultimately it's just a small element set here and you can see that i'm outputting the the data was it called post or posts so data posts data posts and so you can see that i'm outputting this the title and the excerpt and there we go so all i've done is i've called um i've sent off a request with the slug i've made a match and then i return the individual item so what i need now is some links because on the home page which is the post here i need to actually create some links to the individual items so what's happening here in the post page we're looping through all the different posts that's returned from the database so this is just going to be a simple case of just extracting the slug item from the post so you can see what i've done here is i've just created this link so i needed to bring in link up here so i've just created a link i'm not using nav link i've just removed nav link we could integrate into nav link but i've just kept it nice and simple for now we've created a link here we've wrapped it around the media the card media which is the image that gets shown and you can see here i've just created a link to posts and then post slug so that should send us to the post page and then the slug will be collected and sent off and so on so let's just go back to our react application here we go the home page and we we're going to click on the images here which have been generated by an api so we click on those and there we go so we've got the individual post and so on well thank you very much so we come to the end of this view sets and routers hopefully i've given you enough information to understand the basics of view sets and routers and in addition to that hopefully the examples i've provided did help to kind of expand the point and just showcase the basics of view sets and routers
Info
Channel: Very Academy
Views: 10,918
Rating: 4.9536681 out of 5
Keywords: django, django rest framework, django framework, django rest, djangoproject, django react, django python, rest framework, django cors, django tut, django tutorial, django 3, django examples, learn django, django beginners, beginners django, django 2020, django example, react, django and react, viewsets, django viewset, django router
Id: dCbfOZurCQk
Channel Id: undefined
Length: 38min 52sec (2332 seconds)
Published: Wed Sep 16 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.