Next.js and Django Fullstack Airbnb Clone - Part 3 - React, Tailwind, Django Rest Framework and more

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
okay so now it's time to start working on the back end in this task I'm going to set up Docker for Jango and use postgressql and I'm going to install janger framework course headers pillow and a few other things that we're going to need but first of all what is Docker and Docker compos Docker is a platform designed to help developers build share and run container applications they handle the TDS setup so we can focus on the code and Docker compos is a two that we can use to define and share multicontainer applications meaning that uh we can have one container with postl that multiple Chango application can use okay so I'm just going to jump right into this and in this part I'm also going to try to use this diagram here and draw a little bit to explain a little bit more how Docker D Jango and simler are connected but we can begin by setting up docker the website for Docker is do.com it's free to use personally similar like that so you can head there install it and make sure that you have it running when Docker uh desktop is running we are ready to start okay so now I have Docker desktop running here and we're ready to start so I'm going to head to the command line and split the screen here if you don't have split option you can just use two windows and then I'm going to go into doents project and Jango um BMB now you can see here that they have the demo images folder and the D Jango BNB folder the Jango BNB folder is the front end so I want to create a folder called back end so MK there back and then I can go into this and this will then be the root uh folder for the whole backend project with the docker file and similar and then in here I can create one more folder MK D Chango BNB back back end and go into this and this will then be the D Jango project um in here I want to create a virtual environment where we're going to install Jango and we need Jango just to create a project actually uh if you already have Jango installed on your computer you can use this so let's just run python 3-m van which is virtual environment and then EMV which be which will be the name of the virtual environment um so now that I have this one I can activate it by saying Source EnV bin activate and now that this is activated means that when I use the PIP command to install Jango it will only be installed into this environment and nothing else so pip install Jango um yes P install Jango hopefully this will install 502 which is the current newest version of Jango so that that's installed and a few other dependencies that Jango has and now that D Jango is installed we can create an EMP project by saying django-admin start project and then the name which is Jango BNB uncore backend and Dot because I want to install it in the folder that I am so hit enter that means that now I have the environment the manage p and the sub project folder which contains the settings and similar if I open this in Visual Studio code it might look a little bit easier to understand so open folder then I can add the back end so in the back end I have the jungle project with a typical manage p and then there we have the settings and then we have the environment here nice so next step then is to create a requirements.txt file and this should contain all of the Python packages that we want for this project right now it's only D Jango um let's find out which version was installed by saying pip freeze and you can see it's 502 if you have a slightly newer or older version that will probably work and then inside this D Jango BMB folder the top one we create one more file called requirements.txt then I just paste Jango equals equals 502 and this means that we're going to when we install this for example the server and similar we will only get this version of Jango which means that it it will be the same uh Jango version on all platforms great so now we have created a new project Jango is installed and similar so then we can create the docker file so in the same folder as we have these two files create a file called Docker file with no extensions remember the capital D um first I want to pull an official image for uh python so from python python colon 3 .2 um let me check what's the newest version of python python 3 Slim Buster official image Python 3 let me just see what version we should use um python slim Buster I think we on 312 or similar okay can see the versions or tags that we have here so it's 313 and we can use the slim not sure what the difference between all of these are but let's just use slim so that means that I now can copy this go back to here and just paste it in like this now we will get the slim version of 313 which is sort of the base for the whole Docker file and then we need to set a work directory inside this Docker uh Docker container work there SL USR slsrc Jango BNB backend so now this will be the poth inside uh Unix system and then on the next line we want to set an EnV uh variable e andv python don't write bite code one and this prevents python from creating the pyc files you know the pyc that always is in many projects we don't want them in here and then we want one more EnV Python and bued one and this prevents python from buffering SD out and SD R ER and what this is that um when python buffers output it collects certain amount of data before it writes it to the terminal or to a file and this buffering Behavior can cause delays in seeing output especially when running Python scripts in certain environment like Docker that's why we want to set this to one because we don't want to buffer and then we want to make sure that pip has the newest version of um of itself so we are on run pip install D- upgrade pip so it just upgrade itself and then we a copy do/ requirements.txt dot so what this does is that it copies this file which is in the same folder that we are now and into this folder here and when that is done we say run pip in oops lowercase pip install d r requirements.txt so this command will then install everything that we have in this file and when all of that is ready we can just say copy dot dot so this will copy the entire Jango project into this folder to work directory okay so we can save this for now we will soon come back and actually use this but before we use it we want to create a a a a Docker compose file this should not be in this folder but in the root backend folder here so just call this Docker compost. yml yml is yaml which is a sort of scripting language with very ugly syntax but it works for this purpose so what we want to write here is version colon 3.8 and this tells Docker that version of yaml that we're going to use or version of Docker maybe is 3.8 and then we want to create um sort of a container or a service inside this composer here so to do that we say services and we want to create a service called Web this will be the Jango project these Services need certain commands or properties to build and run and similar so let's begin with one called build and this should just say do/ Jango BNB back end and this folder here is the folder here so you don't have to think about this or sorry the folder that we copy into this which is the jangle project and the command we want to run command is python manage Pi run server 0000 0 colon 8,000 so this command will start the development server on this port on the local IP address for the docker container so we can now access it from the outside soon at least and then we want to set up something called volumes property Dash and then slash Jango BNB backend slash colon SL USR slsrc SL Jango BMB backend slash and what this does is that um it help us helps us persist data and tells us that the things in here should persist inside this path here and then we need to tell the service what ports should be used and that is 8,000 8 colon 8,000 so this is then the port in Docker and this is the port that should match the one you have here and then the last property is the EnV file this should be/ Dov uncore sorry Dev so this environmental file here should um in this project contain for example the password for the database if you are debugging the secret key and similar and since we use EnV DOD uh it's easier to understand that the variables we put in there is specific just for development so if I save Now open up the browser then inside the same folder as this one in the backend folder we create a new file called EnV dodev so we can set three environmental variables here the buug equals 1 and secret key equals and this doesn't really matter what you call here in development so I I can just call my code with Stein you can call F Fu bar or whatever you want because it's doesn't have to be secret since it's just local development and then we set up something called Jango allowed host equals Local Host 1 127 0 01 do one and one so these are now um addresses IP address and that are allowed to use this server or Jango project soon we will put this into settings.py I hope I don't go too fast forward here I will soon draw in the Eraser app just to show how things are connected um the last thing before we do anything more here is to just open up settings. p and remove this comment and import OS because now we want to read variables from this file so instead of putting out this secret key here as you can see here it says insecure because it's not secure right now we want to read the variable that we have here which should be a secret key on production and then here we can just say os. Environ do get secret key this name needs to match this name then we have the debug variable this is a little bit different since this is a Bine so we need to tell python to convert this to bin true or false os. aniron doget debug and the default value for this should be zero so by default this is false which means that we are in production which means that error messages and similar will not show in the browser but since we are on dev we set this to one which is a true value and that means that we are in debug mode and then we have this one os. Environ do getet Jango allowed hosts uh oops do split space so what this does is that it takes this string here split it by this space and this space and create sort of a array that looks like this Local Host one to7 Etc so it generally just creates this list there and save so now the setup there should be ready and we should be able to start building this container and hopefully everything should run and we can test just want to go in here and draw a little bit here so first of all we have a computer like this this is our computer let me write up here computer doesn't matter if you have Windows or Mac or whatever everyone has a computer and then in here we have a Docker container or yeah a Docker container I can add a label to this Docker container and oops and this Docker container can include services like Jango it can include services like postgress uh ql and there are actually sort of no uh limits to what this can do you can install a full version of B do you can install engine X gunicorn Etc and some of these we actually are going to install later in this tutorial um when you install these in this container the computer doesn't actually know anything about what's happening in here it only can read what you put in the in the port 8,000 which is sort of a server running on your computer on your computer you have this env. Dev file with the with the environmental variables these variables can be read by Jango container and since this D Jango sorry this Docker container reads from this EnV file Docker postl and similar can then read from this Docker container so as you saw here we we read this file from here and then this settings.py doesn't read this file but it reads the contents of what you have here which is put into this service so I might not be the best to explain everything here but hopefully it makes a little bit sense so right now we have this Jango which is this service here and soon when we set up post SQL we will set up that below here so we could actually say services like that so this Docker container contains a lot of services if we set up one more Docker container that Docker container can talk to this post SQL if you wanted to do that so you don't have to install and create a new postco SQL server for each jungle project that you have on your computer okay I will come back more to this later when we install more things here and when we start using the API and similar okay anyways we have set up everything here so let's go to the terminal just deactivate the environment deactivate cleer and then to build uh this Docker composer is just a Docker Das compose build and then this will download and install everything you need whoops load matter failed to solve okay maybe I couldn't use the one that I copied from here uh but why not okay so it's up and running again let's try to just run the command again yes so now you will see that this will download python 3113 and probably a few other dependencies that Jango or sorry that python has to run um no okay my internet clicked again okay three time is a a charm hopefully yes now the downloading seems to be working so now this will download everything we need to run then you can see here these other commands started to run work there these are coming from the docker file with the you can see work there set up there and now it's in upgrading pip it's installing things from the requirements file writing image naming the docker back end web blah blah blah Docker scan okay looks like everything worked so let's open up here here again images now we have an image there and inside containers is nothing yet because I just um built the image and this image actually sharable so I could share it with you I think that's how it works uh but let's start try to run the container and see if we can access the Jango website so Docker comp docker D compose Das up sorry Docker compose up- D dasd makes it run in the background by the way um so looks like that's okay let's open up the container status exited that's not good but uh let's try without the dashd to see if there are any errors can't open file no such file or directory okay now okay let's go up one folder I have to be in the docker compose I think um let's try running do compose up again no it still doesn't work so I think there is something wrong with this part and everything there so just have to look over what I have done wrong okay so the problem was I had a space here it was not supposed to be there when I saved this then run the command Docker compose up again you can see that everything started and you can reach the development server at 0000 8,000 but for us it will be Local Host colon 8,000 and there you have it the install worked successfully congratulations perfect which means that now the back end is not set up finished but we have D Jango running at least perfect let's set a postgressql so let's go back to visual studio code and then inside Services here we can create a new service called DB for database image this image should just be called postgress colon 15 soq version 15 and we want to set up a volumes for this as well remember this space postgress data colon SLV lib SL postgressql SL data and then this is where the data will persist inside the environment so that you don't have to recreate databases and similar every time you start this then we need to set up a few environmental variables so Environ environment the name is post agress user and the name for this user can just be postgress user then we need to set the postgress password equals post password again this doesn't need to be secure because we are just in development it's a little bit more important when we going live and post grass DB which is the name of the database it can just be Jango Jango BNB or you can call it whatever you want if you want to change it then you need to set up one more thing here so it's not it's outside the services this is called volumes and this will then inside Docker desktop register it in here so it will actually be loaded from here every time we start this container and then we just pass in postgress data colon so it looks a little bit weird but it actually is correct um right now these do not speak to each other but they can speak to each other so let me just rename this to DB so we know which one this is inside there web uh right now these uh don't know that they exist but we want to have a link between these and this link can be created by adding one more property to the web service called depends on and what this depends on is DB which is this name down there so we can save this now and that's what we need to do in the docker compose then we need to add a few more variables in the environmental file so first of all we can set SQL Dash sry underscore engine equals Jango db. backends do postgress ql so instead of using um whatever is there right now right now we have the Jango DB back and SQ light 3 but we need to specify that we're using postest ql you need to specify which database we are going to use database equals this should come from here Chango BNB then we need to specify the user SQL user this user needs to be this user SQL host sorry password first password this needs to be this one and then SQL host which should be DB this DB is this one or this one which should be the same and then SQL host sorry Port equals 5 432 which is the default port for post ql so we need to specify both here and here so um the docker sorry the services up here reads it from here and this DB reads it from here so they still need to be the same for now um and then we just need to configure settings to use the variables from here so instead of saying engine like this we can say os. Environ doget SQL andin which is um not there uh this one here variable then we need to SP the name of the database os. Environ doget SQL name sorry SQL database um can just copy and paste a little bit now you need to specify the user the SQL user um we need to specify the password pass word SQL pass word um we need to specify the host SQL host and the Port Port and SQL Port so these six variables here these six name you see here should match these six here so then we can save this um we also need to do one more change to the requirements.txt because um for Jango to work with um post SQL we need to install something called psychop PG 2- binary uh and this is a python package for speaking with this type of database the version we want to use is 29.9 which is currently the newest version of this um so what's good about specifying versions here is that if you to do that you will be sure that you're using the same version of the software that I am using so let's try to rebuild this image and use it so just stop it like this and then say Docker Dash compose up D- build so now this will rebuild it and start it so now this will pull post SQL 15 and install it um I don't think it will do anything with python now because we already had it at least it was cached so you don't have to delete download it more than once so this download seems to take a little bit time okay I need to just stop if this happens to you to you can try to stop the docker desktop and restart things so I'm going to do that now you need to start it again it seems hopefully that will work so now it's starting again okay let me try to run the docker compost up D build again so now it's downloading post SC 15 so now it looks like it's going forward yes perfect so now it's building and it's going through this here again with the work there upgrading pip um okay so service web failed to build let me just see if this version is the correct one psychop PG to Binary 299 okay I might actually have used a two new two new version of python okay um let's go back here again find python 12 sorry about that overview okay so copy this name instead said 3122 slim Bulls Eye go back to the docker file and paste that there save um now we can try to rebuild everything again so now you can see here that it's using an little bit older version of python so now it's installing c p 2 and Chango so it's copying the project export in and it should be running now it's starting the database good good good good so let's try going to Local Host 8,000 again okay so we have D Jango running now and hopefully Also postgress ql let's stop this again by hitting contrl C and what I want to do now is the run the migrate command because you can see here have this warning you have 18 unapplied migration ations and to run this command inside the container we can use Docker D compose exec for execute VB which is the name that we have there which is this service python manage.py migrate let's run it okay that's good we don't want to re build this now so we can just run Docker compose up and now we don't have this war yes we still have the warning why didn't this work okay but it doesn't really matter right now we can fix it soon uh what I want to do now is to create a new file called an entry point and this entry point should actually run this migration for us and also make sure that post grass is running um so if you just go here now we can see on the image that both of these are in use and in the container um actually said because I stopped it but if I run this here command starting in the background you can see that both of them are running great so let's go back to visual studio code and work on this entry file um so inside we we have manage.py and requirements which is this folder here we create a new file called entry point Dosh which is shell F shell script and the first thing we need to do then is Hash exclamation mark SL bin slsh just to again tell the system that this is a shell script and then we can write the if statement there to check if the DAT base name it's the correct one so if uh dollar sign database equals just one equal postgress then we go into this Loop here and say echo check if database is running and to check this we are just going to use something called net cat which is something we are going to install into Docker to test that this is up and running now can say while exclamation mark NC which is netet DZ and then we pass in the SQL oops SQL host and the SQL Port remember this semicolon do and while this netcat can't connect to this we go into this while loop here says sleep 0.1 so I'm just make this system sleep for 10 milliseconds before we use net cat again to test if this is up and running done so when this is done we just continue and now we can say Echo the database is up and running smiley face and to close the if Loop we say fi which is just if backward and then when we know that the database is running we can run a python command python manage Pi migrate and then we say exec execute dollar sign at and then the te tick again and in the shell script this here um is a special parameter that represents all the positional parameters passed to the script or a function so for example if we run entry Point Dosh space hello then one of those arguments could be put in here if there are any so we can save this so now we want to uh change the docker file again to actually use this entry point and to use this entry point you need to install and use NC or net cat so below here we can say run a apt-get update just to update everything on the server and then apt-get install Dy oops install Dy netcat so you can see here netcat is just NC and then we run the PIP and install everything there and then we after everything is installed we want to copy the entry point file into this as well so copy do/ entrypoint.sh so need capital letters okay um dot because that's this work directory and when that is done with a run s-i take s slash back slash uh back SLR dollar sign back SL SL G so what this does now is that it um um here is something wrong um said- e s/b SLR dollar sign SLG and then we write the content from this into USR slsrc SL Jango BMB backend SL entry point. sh and then we also need to make this file executable so run CH mod for change uh modification plus X this will make it executable slash USR SRC Chango backend SL entrypoint.sh so now this can be run and then when everything is copied over we can set the entry point here and then we just POS in SL USR slsrc SL Jango back in BNB entrypoint.sh so now this Docker file will actually run this last thing you need to do before we test this is to set an environmental variable at the bottom here is at database equals postgress and this name here is what we are reading there and this should match this one so let's try to rebuild this again so to compos up Das Das build so this shouldn't take too long now everything need now is to install netg as you can see there so now it's upgrading pip installing the requirement Jango AC 2 y y y there you can see it made it oops there's something wrong failed to create unable to start container permission denied I might actually need to make it executable here first so let me just try to run CH mod plus x/ Jango BNB backend entry point Dosh um I think that should be it um I think I wrote it correctly here C Mod plus X yes try to rebuild again okay that looks a little bit better at least blah blah blah so ready for startup stop startup exited with code two so there's something wrong with the back end web syntax fi unexpected okay I probably forgot something in the entry point I think that in this if statement here I should actually on the next line say or then like that so in this shell script I think it should be read in now let's stop start or build again unexpected then H let's go to the script again just need to look over everything here maybe this actually should be on a separate line let's try that by stopping and building again yes there that looks better so if I scroll up now you could see some of the commands check if database is running the database is up and running and you can see here it's running the migrate perfect okay so then we need to do or we can actually go back to the Todo list because we can set this to done so now we just need to install Jango rest framework course header Etc so if I go back to visual studio code and I find the requirements.txt then below here we can install dj. rest- equals 4 sorry equals equals 40 0 and we want to install Jango D all o equals equals 052.0 we want to install Jango course headers 4.3.1 4 one and I will come back to these later in this tutorial and explain more what each of them do the Jango rest framework rest framework version 34.0 and the Jango rest framework DS simple J2 jble jble WT 53- do1 and pillow pillow is a python package you need to use images in jungo 10 to Z so I think that is everything for now and we can install channels so channels equals 40 this is something we need for the real time and defy defy 4 Z Z so I think that's it so if I just stop now rebuild it again then hopefully we should have everything that we need so we can continue building this awesome project great now you can see that there were no migrations to run and the development server is running and if I go here refresh everything is as it was so I just want to stop this now and I want to run this in the background like that so it's still running here as you can see now perfect so then I can go to the to-do list here in eraser oops closed it and set this to done okay so now that everything is installed um the docker container is running we have post SQL database and similar we can start working on the user model so to do this we need to create a new Jango app so I can't talk or I can't use uh the python here to create a new app maybe I can use Docker compose EXC web python manage.py start app and then use uh user account so now you can see here we have the user account which is a Jango app where we're going to specify the Jango model and similar for the user account um before I start defining the model so as you can see here I have it now inside this Jango project let's open up models. p and start working on this so I want to install uh sorry import a few things first so first we can say import uu ID because I want to use this for having um different types of IDs for the users and then I want to make it possible to use uh things from the settings file so from jango.com import settings so now I can access variables from the settings file and I want to import a few things from the builtin user models so from Jango oops. Contra do. model import uh abstract base user and I want to import permission mix in and user manager a user manager is for example when um I can show down here if you say user equals user. object. getet pkal 1 this object here is a manager and we're going to create our own or at least override the built-in to change a few things um can make this a little bit wider so they can see everything I've imported so far and then I want to start building it down here so I can say close custom user manager we can begin with this one then we just PA in user manager so now we sort of inherit everything that this has already but we want to override a few of the functions or methods as it's called here so defcor create user this is one we want to override self name email password and if there are any extra Fields what I want to do here is to check that first of all if there are an email that we can if not email that we can race an error by saying race value error you have not specified a valid email address this will show in the back end first of all and then we can say email equals self. normalize email pass in email this function here normalized email already exists in user manager so we just reuse it to to make sure that this email is valid and that U there are no funky things in it now we can say user equals self. model email equals email so now we actually create a user name equals name and extra Fields um we can't pause in the password here because we need need to use a function for this by using user. set password and pass in password and since we use this here it will be salted or hashed or whatever you call it now we can save this user Dove using equals self. DB return user so this is almost what the default one looks like but since we want to use name and email and password instead of of the first name last name and username Etc we need to override this and then uh we create the actual function that should be able to be used from the command line and similar So Def create user self name equals nonone it should default to nonone email nonone password none and then the extra field s and in here we can say extra Fields do set default is sta to fals so when we just default set all user that is created to not be staff and let's copy this and that is super user to false as well because we don't most users we create should not be a super user and return self doore create users now we use this method up here pass in name email password and pass in the extra Fields if there are any and then we want one more called create super user So Def create super user oops and this command here or function is the one we typically use when say python Meed by create super user so we want to create our own here create super user and self name equals I can actually just copy this one copy up to there because they are very similar this just have these two values default to true because when we create a super user this should of course be true so you can access the admin area and similar so that's the user manager hopefully it should make sense if you have any questions about this feel free to leave a comment below and I will answer as soon as I can so now we create the actual user database model this is not something that will be created in the database or anything it's just something that Jango knows about so here we want to pass in abstract base user and the permission permissions mix in so we reuse much of the built-in things first we can use the ID field ID equals models. uu ID field um this should be a primary key so primary key equals true and the default value for this should be uu id. U id64 so it now uses the thing we imported up there and editable equals false and when you set something to editable it will not show up in the admin interface and similar because this is not something you want to change this is automatically generated I have the E field which is a models. email field and unique equals true because you don't want to have a two users with the same email address so now Chango will automatically validate this for us name is a Char field can set the max length to 255 because we don't need to have any restrictions there blank equals true and null equals true in case a user don't want to fill this out there are many weirdos out there Avatar equals models. image field so now we want to use a different image sorry different field type called image which takes a parameter called upload two and we want to upload a folder called uploads SL avatars like that um in settings we're going to Define where this is on the server before we start creating this models and similar but we don't have to think about that right now is active equals models do Bolen field so this will um if this is set to false then the user will not be able to log in default equals true actually is active um should be set default to false so that in no we set this to true sorry set it to true but if you want want email validation and similar you need to set this default to false is super user equals model do Bolen field default this to false copy and paste is oops is Staff default defaults as well then we want to know when this user joined the project or created account or date joined equals model. dat Time Field Auto now add equals true Auto now add means that when this is added to the database this entry now will be added to this field automatically so we don't have to think more about that last login equals models. date oops date time field and this can be blank equals true null equals true um because we don't know when the user um when you just create an account you are maybe not logged in so it could be empty but every time we log in this should be updated then we say objects equals custom user manager so this objects here is the typical user doob we could call this um custom object if you want to do that and keep using the object that comes default but that usually becomes a little bit of a hassle so let's just call this objects and then we want to specify uh which of these fields is the field we are going to use for logging in so username field equals email this one and which Fields is the email field email field field equals email and the reason I to specify this is because it's um something that the abstract base user uses so we just need to have it here as well and required Fields whoops required Fields equals this should be a list name so um these are sort of already mandatory but we set this required as well and that will make sure that when we create a user for using the create user command this will be prompted to the user and yes um that should be it for now I think we can save this and update the database so Docker D compose xac web python manag by make migrations no changes detected of course not we need to tell Jango that we're going to use this app so inside installed apps let's add user account here but um what we also need to do now is to make sure that we are using this model as the default o model so I need to set one more thing here o user model model equals user account do user so this here points to that and this points to this model here um I think there is a little problem here now because we should already have a user model that since we have already run the command python migrate module you uid has no attribute uuid 64 maybe I did a typo yes I definitely did it's supposed to be u4 um let's just run this and see what it says create model user okay but uh we want to remove everything that was there before so I think we can say flush DB and maybe just flush and yes you can see here this is irreversible so this will destroy everything in the database and return each table to an empty state are you sure you want to do this yes thease couldn't be flushed possible reason the database isn't running blah blah blah blah blah okay that's not good um okay look at output just run this command and see what happens settings module properly configured yes it's probably because I'm not inside the environment so I need to delete the database um okay let me just actually not sure how to flush this since this this is not working okay I will just have to stop this container and I want to delete these volumes that are connected to the database image okay try to delete this one is in use blah blah blah okay stop everything let me just delete everything okay remove remove and remove this volume okay so now everything is blank again sorry about all of this mess so let's just rebuild the container Docker compose up dash dash rebuil of course not just built so now this will install everything again download if it's not there yes since I deleted the image I had to download everything again but as you can see it this didn't take too long now it's creating the new database table and you can see here it's actually using the user account migrations so now it is running local host 8,000 yes it it's working perfect okay so I can stop and I can run this in the background again toer compos up dasd perfect okay so now we have the database table and everything looks okay so that means that now I can stop this and we can create a new app for the properties so just like we created that other app the user account app we can use this command again uh property so doer compos XA web python man P startup property great and then we go back to the code and then we can tell Jango back end that we have a new app called property but before I do anything else here let me save this for now um actually I want to go back to the Todo list and create a new app uh sorry a new to-do called configure drf course Etc because you need to do a few things to the settings file so we can just do that before we do anything more fun so inside here we need to set up a lot of different things um we need to specify something called a site ID set this to one this has to do with the all all o and make it possible to log in we have set up this so that can just be like it is um I want to set website website URL HP col sl/ Local Host 8,000 this is just URL for the server in case we need it we can set up the simple JWT WT create a dictionary one variable access token Lifetime and the value for this should be time Delta dot sorry parenthesis minutes equals 60 so the lifetime for Access token is 60 minutes so after 60 Minutes this needs to be uh reactivated you can see here I get error now because we haven't imported time Delta from date time import time Delta so the error is gone then we need to specify some call refresh token oops refresh token lifetime how long should this live time Delta days equals 7 so you can stay logged in for a total of seven days and you use the refresh token multiple times to get a new access token and then rotate ref re whoops refresh token this can be default set to false um because it doesn't really matter that we don't have to refresh them I have in a database that uh different tokens can't be used again Blacklist after rotation this can also just be set to false since we don't have this here set to true this doesn't really matter and update last login true so this will then update this field here automatically and signning key signing key um this um okay maybe this is also something we should get from the environmental file let's come back to that right now it can just be a complex key so we remember to back to this algorthm RM that's wrong Alor yes that's right age s 512 so which algorithm to use for these tokens comma so that's was the configuration for that one um then we need some more configuration uh account user model username field so which field are we going to use let's just say none that's just the way it is for this one account email required equals true and account username required equals true soorry it Bea because we don't require the user to have username the user to just have an email address account authentication method is email and account email verification equals none because we are not going to uh require email that you have verified it okay so this is then for the authentication to work how it's going to work and similar then we need to specify the rest frame workor equals creating new dictionary and then we set up something called the default authentication classes and the default authentication Clause to use here is restore framework underscore simple JWT do sorry do authentication do JWT authentication authentication comma actually this should be a to and not d sub dictionary like that and we also need to specify the default permission class so default [Music] permission classes again use parenthesis because this is tle restore framework do permissions do s authenticated and what this does is that this is what we want to authenticate users with the Json web token and the permissions that we want to use is that the user should always be authenticated to access the data then we need to configure course allowed Origins so course uncore allowed Origins equals create a list a HTTP col1 1270 01 8,000 this will be the back end but let's also set up for the front end which is 3,000 and um this just make sure that a request into the API has to come from one of these addresses if not it will be rejected that make it much easier to prevent people misusing your API and similar and then rest or equals so then we need to configure this to use underscore JWT true because we want to use this and J WT or HTP only to true no so sorry false okay so then we have configured the rest authentication as well and then we can set course uh allow Origins H this is not anything I need okay let's just keep it like this for now then inside install apps we have these that we have already but we need a few new things so we need to add a rest frame work we need to sorry this restore framework restore framework. token rest framework dot uh sorry underscore simple JWT so there's the dot there's underscore just by the way we want to use all or we want to use all all or do account which is then the user model that this will uh use djore rest or djore rest or. registration and last but not least the course headers so this is for the rest framework so that we can use API these are for authentication between Jango the rest framework and similar and how to use the tokens this is for allowing things to come from the front end so that's it there then we just need to add one more thing here above this common so on the third line here we can say course headers do middleware do course middleware okay then I think all configuration is ready let's run this command just see there are no issues right now at least you can see here now I have five unapplied migrations and that is because when we added this they come with some migrations file so we need to run the migrate script again so we can just run do compost EXA web python manage P migrate that did not seem to [Music] work H do I need to build it again in order to run that [Music] command let's run this do command up build just to make sure we haven't added any data yet so it shouldn't ruin anything at least so there we got the new migrations the account and all token and the project is now running and there are no warnings great if I refresh the project is still working nice um so that means that now I can configure or set this task to done because now we have configured everything in the back end um yes so let's continue with the app for the properties um this is the model for the user okay so everything there is now set up but we need to do one more thing here in the settings file and that is to set up the media files so we have the static files but we also need a media root equals media slash and the media sorry this was supposed to be media URL and then the media rout so where on the server should we put the files I want to have this in the base there slash media save so this here will now point to this Jango folder here and media will be created the first time we upload a photo and then here where we have the avatar for the user upload Avatar will be put inside the media folder there okay so then I can set this task to done so now we can continue setting up the app for the properties so let's go back to visual studio code okay so Jango is running there we have the model for the user so let's set up the model for a property so we can begin by importing uu ID here as well so import uu ID and I want to use some settings here so import jango.com sorry from jango.com import settings this should be like it is and then I want to import the user model so from user account. models import user and then we can set up a Class Property pass in models. model and we can copy the ID Fe from here since it's a little bit long and we don't have to write it again still just the same then I want the title field which is the name or whatever you want to call it for the property equals mods do uh Char field MOX length can be 255 we don't want this to be blank so it can be like this I want the description field which should be a m. text field and I think that this should also be required so just keep the parenthesis there EMP um we can set the price per night equals mods do integer field this should also be required integer field is easy for whole dollars you usually don't have 99.99 and similar if you want to do that you need to have a float field instead but droms equals mods. integer field so we need to keep track of how many bedrooms you can allow um bought rooms um maybe number of guests here you can add more Fields if you want to do that um I want to keep track of which country this uh property is in So Country equals models. charfield set the max length to 255 and copy this I want the country code so sort of for example n o for Norway or us for United States so it little bit more Universal this can just be max length 10 so it doesn't take up too much space I want to have a category field so let's copy this one category this is just a very simple string field um we can I want to have a faved here but we can come back to that one and instead use the image equals models. image field I think this can upload to uploads slash properties this is also required because I want all of them to have a image landlord this can also be created at but landlord or host it's very easy to understand what to do so models. forine key and we point up to the user here user and then I want to set something related name equals properties so it's easier to get all of the properties belonging to one specific landlord on delete models. Cascade so if we delete the user we also delete all of the users properties um and I want to know when this was created so created at equals small. dat Time Field aut to now head equals true so this just handle automatically by Chango so save this then we can update the database stop this this one find the make [Music] migrations and migrate hopefully this is working there are no output but yes let's see if I take away this just [Music] up no migration your models have changes that are not reflected in migration so it won't be applied run make migrations okay so it was not applied um but why are there not executed hm okay so let's open up this entry point again maybe I just need to add them here python manage Pi make migrations and then afterwards we run that um if I now run this one will it go into there yes now it migrates and creates new tables and it looks okay great so then I have to don't have to rebuild as long as I have it here in the entry point that's good to know okay so now we should have the table the database table for the property so um in order to get this and show it in the front end we need something called A serializer and A serializer comes from the jungo rest framework and it takes data from here and convert it into Json format and so let me open up here again and inside this property I create a new file serializers pi and you can call this whatever you want but this makes sense and it's easy to understand what it actually does so from the rest framework we import a function called serializers ser serializers and then I want to import the property model we just created from do models import property and then we can create the property list ser izer so close property properties we can have this plurally list serializer serializer do model serializer because we want to base the serializer on a specific model to do that we just specify a matter class here say model equals property so now the serializer know that this property or sorry this model is this one and then we just need to tell which fields we want to get there and I want the ID field I want the title field I want the price per night and I want the image URL so then you may be asking where this this come from we only have a field called image so I want to create a function called image URL and that function should look something like this def uh image URL POS itself and then we can say return f f and then tick because we want to have a formed string here and say settings. website URL this will then point to the variable we created here previously this one so we get this or address automatically so settings. website URL go after this curly Braes create one more self. image. URL so now we just point up to this field and we get the URL from that field save and that's the serializer for the list of uh items or properties as you can see here we get image sorry need to go to our project which is there the image the title the price per night so the ID is what we use to go in to that one so now we know um how to get convert the data into Json format but we still need to create one more file here called API Pi so we need to use the serializer to actually make this URL available from the front end so we we can begin by importing few things from Jango HTTP import Json response and we need to import a few things from um Jango rest framework so from rest framework dot decorate decorators import API view we need to import the Authentication classes decorator and the permission [Music] permission classes and um that's it there we can then import the model and the serializer we just created from Models import property from serializers sorry do serializers import properties list serializer then we can set up the view so now we're going to begin by using this decorator here to tell Jango that we are going to create an API view API uncore View and the only request method we want to use or allow here is get so if you try to post to this view you will just get an automatic warning and um in settings. p uh we said that you should Auto um by default be registered and authenticated but you can visit the website as a guest and I will need to tell this specific view that you don't have to be authenticated so let's just put in an empty list there and the same with the permissions classes you don't need any permissions to view this page now we can say def permission permission then we create a view bying def properties underscore list posing the request parameter just as typical Chango View and then here we can say properties equals property do objects. all so then we use this model to get all of their properties from the database and then we use the serializer serializer equals property properties list serializers pass in the properties we got from the database here and say many equals true because this is a list of properties and not just one object now we can say return Json response and create a dictionary here um that data serializer do data so then we pass everything in to there and then this view should be able to be used and then we need to do one more thing and that is to create a URLs file urls.py because I want to keep things as clean as possible and you do that by having a separate urls.py file for each of the apps you're going to access from the front end so from Chango URLs import path and from do import API so we just import the whole API file and we can set up the URL patterns list and when the pot is empty like that then we want to use api. properties list name API properties list you don't actually need this name but I like to name them anyways so the last thing we need to do then for the back end is to go into the main url. p as we have here remove this ugly big comment and at the end here we can say po pot like that and when the pot is API SL properties slash then we want to use include um property. URLs so I get a warning here we can import this together with PA from Django URLs so when the address is matches this one it will go into this URL and find out that okay there was nothing more on the URL so the URL is sort of this one and then it matches this empty one and we use this view so let's try to see this in the browser Local Host 8000 SL API SL properties SL then I get empty list because we don't have any data in the database so we need to create a super user so that we can access the admin interface and add a demo property for testing so stop this one and let's try to run create super user that did not work work H can I access the shell no Chango um Docker create super user how do I access this one okay so you see here I need to specify the correct container ID so let's try this Docker EXC okay is that maybe the problem that it's not supposed to be Docker compose no such container web okay that's great remove web from there find the docker desktop containers and the name is actually backend web one let's see if that works no oh no no no Docker EXA space and then the name which was back end web one backend web one and then python manage by create super user so it is not running then run it starting so now it is running let's try one more time create super user why does not end anything work for me let's try this whole ha Docker exac D it please work okay nice so then I'm in the Shell but I want to use the create super user command instead now this is working so command this docker EXA it backend web one backend one is the one I have there back endore web1 and then I need to specify email Stein at code with stein.com my name Stein my password created successfully and this should now be running so let's try to go to Local Host to admin log in with the user I just created nice okay so we can't find the properties here so we just need to add these so if I go here find property admin.py and then say from Models import property admin. site. register property and save save to refresh now it should appear here great let's try to create one first property the description just some random price per night $100 two bedrooms two bathrooms for guests Norway country code and O category fle beach house not sure what this will be but it can be like that for now Stein is the landlord and then I need a image project Jango BNB demo images beach one save so that looks like it was working then I have the media folder uploads properties beach one is there nice so the image uploaded and similar is working great so if I then go back here go to this one API properties then I actually have one in the data now with ID the title the price per night and image URL so then if I look at the task list here set this to done this can be set to done and then I want to make it possible to get the properties in the front end and list them so instead of hardcoding these here I want to actually show the ones that we have in the database so let me close everything here now and and go to the front end to work again nice okay so let me just go to the project there and then if I open up visual studio code I can find the front end code for this so I should have the property list this is sort of where I want to get the data and I will present it in here so let's begin by getting data from the back end so here we need to call or convert this to be a client component so use client because I want this to happen on the client side and then we need to import a few things from react import uh use effect and use State because we need to know when this component is loaded and we need to store data in the state so we can show it on the page from react like that then in here I can say use effect create an arrow function and just pass in an empty array there like that so in this use effect here I want to call a function called get properties so so get properties because this cannot be a synchronous but a function can be so now we can create this asynchronous function by saying const get properties equals as sync and create an aror function like that then in here we need to load data from the back end so the URL is let sorry const URL equals HTTP Local Host 8,000 SL API SL um properties so later in this tutorial I do not want to have this hardcoded here and similar we're going to load it and a few other things but right now it can just be like this and then I think I can just say um oh wait fetch URL um method is get think this is correct and when this is done we can go down here and say dot then response F errow function response. Json so we just uh return this and go to the next step which is Json create a new error function console.log Json Json so now we can see what we get from the server and if there are an error we can just say do catch Arrow so error po it into errow function console log error error so we can sew it in the console what's wrong like that so let me save go here doesn't seem to have crashed at least okay so there are something wrong with the course headers of course of course um I don't think here is anything more info no um okay so let's open up settings. p okay course allow all or Origins equals true maybe that's the thing I need to set nope well actually this is what we can use for development yes good but I still get an EMP response but why do I do that I can't see any list of Errors right now so there refresh so it's going to SL API /properties and now okay now it is working perfect so I can see here I get the data and then have one property there so let's go back here again and then we need to set up a state for having all of the properties so const create a list properties set properties this can just use State and default be uh list like that I think that uh typescript is going to give me an error now but let's see set properties json. data because we want this array and not Json itself save okay so there are no errors still and then down here I want to Loop through the properties that we have here and Implement one of these so to do that use this and say properties. map create a variable property and the arrow function and then we say return because we want to return the data to create here and pass in one of these and we can remove these two so if there are any data now we know that it's the one that comes from the back end yes and each child in the list should have a unique key we can fix that by saying key equals property ID so this property is this variable and now I get a variable because no error because ID does not exist on type never and that's because we haven't specified what sort of type this data here is so that will be the next step to go up here to the property list top here now we can say export type property type so equals uh then here we want to expect ID and the ID should be a string and then we can change this use State here to actually use this property type so use State and then we put it in like this with the um what is this called Arrow bracket I think and then like that and we need to specify that this is a list like that so those type of brackets list bracket in there and then the brackets in there again so then you can see that the warning here is gone now because now typescript knows that we expect to have an ID in this one so when I refresh now this is actually loaded from the server so now we can pass in a property object into this one by saying property equals property then I get a new warning from typescript because it doesn't expect to get a property there so that should be inside here now so at the top here we can say import um property property type from the other so we just import the type we have here and then we also want to specify which properties to put in here so interface this is not type but an interface property props e not equals but curly brace and here we expect to get property value property and this is a property type like that and then we need to tell this component to actually use this list here so we convert this to be react. functional component and pass in the property props and then we are soon ready inside here we create two curly braces and say that we are expecting a property so if I now save go back to to this one the error is gone because now we have this this isn't a property so you don't have to specify it up here but instead of hardcoding the name we can say property. title now I get the war name because you can see it's actually working but this is sort of a warning from typescript because we don't have a title up here so you can say title string save and then this warning is gone and this is working nice so now we can show the price per night property price per night now we add that as well to this one integer no just normal integer or a number number is correct is error is gone then we get the correct value from the database and then it's just the image and to show the image we say remove the hardcoded here and say property. image URL then I get a new warning this is actually just a string as well so we can just say string like this and then I get a new warning because Local Host not is not configured um in the next config because need to tell next uh which um backends or addresses we can load data from so we need to open up next. config MJS so in here in the next config we pass in a property called images create a new dictionary remote patterns create a list and then an object in there protocol http and the host name that we want to use is Local Host the port we want to allow is 8,000 remember this is to the docker and the path name can be SL star star so it's sort of a universal URL so if I save now go back and refresh then hopefully it's loading but the beach is not showing there okay um so there is something wrong with the URL there this should be correct so I think I can just close it let me see if the image exists um I think I need to configure a thing on D Jango HTP 8,000 SL media slash uploads slash properties slash Beach this give me 44 error yes that's correct so if I open up urls.py in the main project then I just need to specify here that I'm going to use this so from Django docon import settings so what we are actually doing now is to use the development server to host images this is not something we need to do later in the project when we are going to deploy this is and we need to import one more thing from Jango doc con. url. static import static and then at the end here we say plus static so use function pass in settings. media URL set the document rout to be settings. media root and save so if I refresh here now I should hopefully see image nope there there it is perfect and so if I then go here again not there but to the jangle project and refresh now this image is actually loading from Ducker great I can try to add one more property just for testing just add some random [Music] information try to use a different image cabin same landlord and save and if I now go and refresh I actually have two here perfect so now we can actually load data from the back end and show it in the front end the code that we used in here is not the best one so I'm going to restructure this soon and set up a service file and similar so I can actually set this as a new to do here create API service file and use it in the properties list but I can add this to done and that was it for this if you have any questions about today's code feel free to leave a comment below and I'll answer as soon as I can see you in the next video
Info
Channel: Code With Stein
Views: 5,950
Rating: undefined out of 5
Keywords: code with stein, django, learn django, django tutorial
Id: zNjyhJ7RPFI
Channel Id: undefined
Length: 110min 4sec (6604 seconds)
Published: Mon Feb 26 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.