Django & React Tutorial #2 - Django REST Framework

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hello everybody and welcome to part two of the full stack web app in python using django and react if you have made it here give yourself a pat on the back not many people make it past the first video so i hope you guys are going to stick around for the rest of them but anyways let's get started in this video we're going to be dealing with django rest framework we're going to be building some api endpoints we're actually building our first database model all right so let's get started by creating our model and then we'll look at the api endpoint all right so i'm here in my models.pi file from my api folder let's just quickly discuss what a model actually is so in a standard database you would have a table you would have rows and columns in those tables and well that's how you would store information now that's no different in django but when we actually go ahead and create a table what we're going to be doing is creating a model instead so what django allows us to do is write python code and then it will interpret that python code and automatically perform all of the database operations for us so essentially it's just a layer of abstraction it makes it a lot easier for us as python developers to write database related stuff and well that's pretty much all there is to it so we're going to go inside of our models here and the first model and actually the only model we're going to have for right now is a room model now remember our app we want to group similar users together or group users together in a room that room will have control over the host's music right like that's what we're doing for this app we're having one person hosting or playing music and then other people join in on this room and while they can control that music so first thing we need to do is make a class i'm going to say class room and inside of here we're going to inherit from models dot model so this is just telling us hey this is going to be a model and notice that models is already imported at the top of our file now inside of here what we're going to do is define the fields that we want to have for our room so essentially the pieces of information we want to store for each room now i'm just going to tell you what these are but try to think to yourself what would we really need for a room what is a room like what comprises or makes up a room well the first thing we're going to have is a code this is going to be a unique code that identifies the room so we're going to say code equals models dot char field like that and character field is saying okay and sorry this is models not model this is going to hold a bunch of characters so our code is going to store a bunch of characters and well that's the way it works now inside of here we're going to say max underscore length this is a required argument to the char field and we're going to say what is the maximum length that this field can be i'm going to say that it can be 8 and then we can set a default value if we wanted to i'm going to set default i'll actually change this something else later but for right now we'll leave it at blank and then we can say unique equals true what i'm typing here is pretty much the constraints on this field so i'm saying okay what do i want this field to look like and what constraints or things do i want to make sure satisfied when i create a new code in my room well first we want it to be unique we want the maximum length to be eight and the default value will be well something we'll put that in a second now before we move on i need to take a quick pause and thank the sponsor of this video and this series which is algo expert algo expert is the coding interview prep platform that i use to prepare for both my microsoft and shopify interviews it's great because not only does it have a great selection of high quality practice questions but each of them come with full video explanations and detailed code walkthroughs start mastering coding interview questions by checking out algo expert from the link in the description and use the code tech with tim for a discount on the platform next each room is going to have a host so a host is going to be equal to a models dot char field the max length is actually going to be 50 and we're going to set unique equal to true as well we're only going to have at most one host for one room so one host cannot have multiple rooms that's a rule that we're going to set here now what is the host field well the host field is going to store some kind of information essentially that relates to our host or that links back to the host i can't really discuss what that is right now because it's beyond the scope of what we're doing in this tutorial but we just need to keep track of who the host is next we're going to have a field that says guest can pause this essentially is the permission that says okay is the guest allowed to pause the music or play the music this is going to be equal to models.boolean field and we're just going to say no equals false which means we must pass a value and we'll say default equals false as well again if you want to look at any of these fields what you can do is just go look at the django documentation there's a bunch of different ones that you can use but i will show you kind of most of the main ones here next we're going to say votes underscore to skip and that's going to be equal to models dot integer field inside of the integer field i'm going to say no equals false and we can set a default value for this as well i'm just going to set it to 2 but you can set it to whatever you want actually probably one makes more sense as our default then lastly i'm going to add a field called created at and it's going to be equal to models dot date time field and this one has a really cool argument auto now add equals true this means we never have to pass the date time to our object whenever we create a new room it will automatically add the date and time that it was created at so i know i went fast through this but these are the five attributes or kind of pieces of information for each room and these are some of the constraints on those pieces of information again i found these fields just by going to the django docking documentation and looking them up now of course you could add more if you wanted to you also add methods on this model so we could say something like define like is host this right and then we take you know like some host and then we check if that's that we can add whatever we want and the basic rule in django is that we want to have fat models and thin views now it's not going to be too relevant for us but that pretty much means put most of your logic on your model so that's what django is trying to tell us to do now i told you we were going to do something for code so my code for the room i want to be random and i want it to be unique so as every time we create a room i want to come up with some random eight-digit code that represents that room and that's what we'll use to figure out hey you know can we join this room or how we identify the room right that's what we're gonna do so what i need to do is define a function here that can generate that code for me so i'm going to call this generate unique code and inside of here we will say length and set this equal to whatever we want the length of the code to be now we can set it to 8 characters we can also set it to be something like 6. let's just leave it at 6 and we'll leave the max length at 8 in case in the future maybe we run out of codes and we want to have more anyways we'll say length equals 6 and then i'm going to say while true and inside of here i'm going to try to generate a bunch of codes until i find one that's unique so i'll show you how this works but this is cool because it's an opportunity for me to show you how we can actually query and look at all of the rooms in our database so first we're just going to go up top and i'm going to import string like that and i'm also going to import random this is because we need to use this to actually generate the random code next i'm going to say code equals and then i'm going to do a blank string dot join and inside of here i'm going to say random dot choices plural and i'll go through this line after because it's a lot and i'm going to say string dot ascii underscore uppercase that's going to give me all of the ascii characters uppercase and the length what do i want that to be well i want that to be so sorry k which is the length is going to be equal to length now i know this is confusing but this will generate a random code that is k-length so in this case 6 and that only contains the uppercase ascii characters that's what this will do you don't really have to understand exactly why that works but we're just going to say code equals that and that will give us that code next we're going to make sure that this code actually is unique and the way we can do this is by looking at all of the rooms in our database and checking if they have a code like this so i'm going to say if room dot objects which technically gives me or yeah plural which technically gives me all of the room objects and then dot filter this is saying okay i want to filter all of these room objects by what well i want to filter it by code and check if the code is equal to the code we have right here now i'm going to count this because what this will do is return to me a list of all of the objects that meet this criteria then i'm going to say if count is equal to zero then we're good we can break and we can return our code so hopefully that makes sense that generates the random code uh and yeah i won't go too much more in depth in this function i think you guys get that obviously if this is not true then we'll just keep generating more codes until well one is unique all right so that's good for models now what we need to do since we modified the database and we added a new model is we need to make migrations so we're going to open up our terminal inside of here we're going to say python manage.pi and then make migrations and you can see we've made the migration so migrations for api and you see what it says we created the room model now that we made those migrations we need to apply them so we're gonna say python manage.pi migrate now boom go ahead apply all migrations notice api is here apply the migrations and we are good to go all right so now that we have this migration done we've created our model we want to set up an api view this is different from a standard html view i'll talk about the difference in a second that can return to us all of the rooms that are currently in our database the reason for this is we have to remember that right now what we're trying to do is we're trying to program a back end and what i mean by back end is just a server that essentially can handle information so handle requests and then give some type of valid response now if we think about it it would make sense that our front end would want to be able to access or check specific rooms right say a user tries to join a room well it needs to look in the back end and say okay you know does that room exist so we need to create some kind of endpoint that can return to us information about the rooms in a format that makes sense we're probably not going to return html code we probably want to return something say like json format where we have key value pairs that our front end can really easily handle look at it and and do things with now you'll see how that works as we go through but the first thing i need to do is create what's known as a serializer class so i'm going to go ahead and make a new file called serializers plural dot pi and what a serializer does is it will take our model in this case a room that has all of this python related code so it has actually you know code equals this host equal this whatever it's in python and it will translate this room into a json response you'll see how that works but essentially it will just take all of these keys here it will turn them into strings and then it will say you know colon and then whatever the actual value is that's stored here it just does that for us anyways what we need to do inside of our serializers.pi file is we're going to say from rest underscore framework import serializers and then we're going to make a class we're going to say class room serializer this is going to extend serializers dot model serializer and inside of here we're going to have a class we're going to say class meta and i'm not going to really describe how this works but we need to define the model that we want to serialize and that we need to import so we're going to say from dot models import room and we're going to say model equals room and then we're going to say fields equals and here we're going to list all of the fields that we want to include in the output or in the serialization now in this case i want all of them so i'm just going to say id and i'll talk about id in a sec code host guest underscore can underscore pause and finally votes to skip now notice that these strings here match what i have in my model so code matches up with let's get rid of test here with code host matches up with host guest can pause matches up with that they're named the exact same thing that's important now we also can return created at i don't want to forget that one uh so we'll return created at right there but you're probably wondering why i have this id well on each of our models we have something called a primary key and the primary key is some unique integer typically that can identify uh the model in relation to all the other models so it's always unique usually an integer and it will be automatically created when we actually insert a new model or insert in this case i guess a new room into our database so even though i didn't define id here there's automatically an id field on every single model so if we want to see that id field i can just put id here and it will return that information to us again this will all make more sense as we get through but let's go to our views.pi now we have our room serializer i'm going to get rid of this main function what we're going to do is write what's known as an api view that will actually let us view a list of all of the different rooms so the first thing i'm going to do is return this or remove this http sorry we're going to say from rest framework and we're going to import generics like that so with a plural and what this will allow us to do is create a class that inherits from a generic api view again all gibberish until we start getting into it so first i'm going to say class room view and then inside of here i'm going to inherit from the generics dot api or sorry dot create api view now what this will do is allow us not only to view all of the different rooms but actually create a room and all i have to give to this view is the following thing a query set which is going to be equal to room dot objects dot all and a serializer class which is going to be equal to you guessed it the serializer class we just made so in here we're going to say from dot serializers import room serializer and that's going to be equal to room serializer now i'm well aware and sorry we also need to import rooms we're gonna say from dot models import room now i'm well aware this all looks like gibberish but essentially what this is is a view that's already set up to return to us all of the different rooms so that's what this will do if we simply tell it the query set which essentially is what do we want to return well from here we want to return all of the room objects that's what we're giving it and then we give it a serializer class that says okay these are the rooms now how do i convert this into some format that i can actually return well we use the room serializer which again is inherits from serializers.model serializer that just knows how to handle this kind of stuff and now all we have to do that that we have this view is we have to link our url to it so it's all going to come together but let's go to our urls page here instead of importing main now let's import that class that we just made called room view we can have both functions and classes being our views here i'm going to say room view and now here i'm going to put room view but i'm going to add one thing dot as view so this is just saying hey take this class and actually give me the view for it that's what that is doing so we're going to put that there we're going to run our server and we're going to pray that everything works fine seems we get an error uh no module named api dot model ah my bad guys let's go into serializers here and rename this models that's correct uh and see if that fixes it okay so that did fix it let's go to our browser now and we can see that we get nothing because we haven't gone to slash api so let's go to slash api and again we still get nothing eh was there another path there let's have a look in our urls ah it's the home page my bad okay so slash api slash home and look what we get some fancy web page that tells us uh detail method get not allowed okay that's fine because this view is actually the wrong one uh my apologies we'll fix in a second but anyways you get the idea that simple little uh class we wrote so if we have a look at it here in view actually allows us to have a view that well looks something like this and notice that these fields right here code host guest can pause vote to skip are the ones that we had in our serializer class that were able to actually put information into so what i'll do first just so that it makes sense when we go to the other type of view is i'll make a room so i'm going to say code let's just go like you know a b c d e f let's say host is just tim like that guest can pause sure and votes to skip let's make that three let's post that request and oh there we go now have a look we get that information right here in this view so it says okay you just created a room it has id1 this is the code this is the host guest can pause this is the votes to skip and this is when it was created at okay so i accidentally refreshed the page and the thing went away but hopefully you get the idea that is how we create a room and there you go you were able to see it before i know it went away because i refreshed but you were able to see that indeed that did work and well there we go all right so now that we have that let me just show you how we can change this view so we created one room and we'll change this to list api view now and you'll notice that if i go back to this url and i refresh it doesn't give me that post form anymore it just gives me a list of all of the different rooms that are in my database so this is extremely useful we'll be using these kind of views for a majority of this tutorial and this is how we set up a rest api we have a way to actually add information to the database which you just saw then we have a way to retrieve it now obviously i'm doing this using the user interface i'm using the browser but when we start setting up react we'll be doing this through requests so we'll just be sending say like a fetch request to an endpoint on the server and then that will return to us some information not in this nice fancy format with all this cool you know buttons and ui but it will give us just this raw data right here which we'll be able to process and then display on the screen so hopefully that is all clear but that is what i wanted to show you in this tutorial how we set up a serializer how we set up a view how we get the models going all that kind of stuff that's what we need to do so now we actually have an api endpoint at where's my urls file here uh slash api slash home and what that does is returns uh the room view dot as view and depending on what generic we use as the inheritance here we will get a different thing showing up now quickly i'm just going to change this to be room because i think it makes more sense that we have this be room rather than be home but that's all i wanted to show you in this tutorial so if you guys enjoyed make sure to leave a like subscribe to the channel and in the next video we'll get into some more cool stuff [Music]
Info
Channel: Tech With Tim
Views: 117,699
Rating: undefined out of 5
Keywords: tech with tim, django, react, django and react project, react and django project, react and django tutorial, django and react tutorial, rest api, django rest api, django rest framework, rest framework django, django rest framework tutorial, django rest api tutorial, rest api django tutorial, rest api django, react django, django react, django rest framework serializers, django rest framework react
Id: uhSmgR1hEwg
Channel Id: undefined
Length: 19min 32sec (1172 seconds)
Published: Mon Nov 09 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.