Flask Course - Python Web Application Development

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
we are going to start learning about the flask web framework now this is a micro framework that allows everyone to build their own web applications using the python programming language and what is so great with flask it allows everyone to build web application with only a few lines of code so it turns the experience of building a website to a lot quicker and easier and in this series of videos we are also going to start with a very minimal application and we are going to push forward until we have an advanced website where real users can start using it so i really believe that in this series of videos we will cover everything that you need to know about the flask web framework in order to come with a great looking website alright so let's have a quick look to the website that we are going to build throughout this series okay so this is the final result of the website that we are going to build throughout this series now the main idea of this website will be to create a marketing system where different users can buy or sell their items so in order to get started i can press in here in that button and then you can see that i see a warning here that i should log in to access that page now if i'm happened to not have a user here then i can basically go ahead and click register now i'm going to mismatch these details a bit so you can be aware of the different error handling that we are going to apply on this website and once i click on create account then we can see that we receive several errors regarding to that website so as you can understand we are going to apply a lot of error handling like in real websites so now i will go ahead and create a valid account here so once i click on create account then we can see that we are inside a real looking web page and you can see on the left pane that we have the available items on market and each item has its name and also its barcode and price and we can display more information about each of our products and as you can see in up top here we have our budget that is set by default to 15 grand so that means that we are going to create a budget system for our users as well and if i go ahead and purchase that item which its price is 520 then you can see that we receive a nice message with the purchase item and we can also pay attention that our budget has been changed over here and further than that we can see in the right pane that now on my items i see that we have a new item that we have the option to sell it so if i'm going ahead and sell this item back to the market then we can see that our budget is back at 15 grand and we can also see that this page is refreshed to what it was before i purchased that item so it is going to be a lot of fun building this website and let's go ahead and get started all right everyone so you can pay attention that i'm inside the terminal in a windows machine but of course don't worry if you use a mac or any kind of linux distribution because i'm going to say the same command that is going to work on those operating systems as well and also one more important point here i'm going to assume that you have python 3.8 or any version above installed and also a ready ide installed that you'll work with so it could be visual code sublime text or pycharm and just to mention off i'm going to use pycharm in this series but it is not quite important which id you are working with just make sure that it is configured with python correctly okay so let's go ahead and create our directory that we are going to store our project files inside it so i will go here and write in make directory and this is the same command for any linux distribution as well and i will type in here the name of the directory that i want to make so it will be flask market and then i will go ahead and use the cd command to change the directory and i will basically type in the name of the directory that we created and now before we go ahead and actually launch this directory in our pycharm i want to install the dependencies that are quite important in order to start building our first flask application so i will go here and use the pip to install some package and you can use basically the same command for any linux machine as well and i'm going to type in here pip install flask and once i have done that then you can see that we got some warnings that are saying that requirement already satisfied because when you go ahead and install flask it is basically going to install some secondary packages that are kind of dependent to flask so just make sure that you hit this command correctly and then there is no any output of errors or something like that and once you have done that let me just clean our screen here then we can basically go ahead and test out if we installed flash correctly and i will do that by type in here flask dash dash version and if you don't see any errors in this command then we should go ahead and try to start our first flask application because we received a correct output that just specifies the versions of some of the dependencies that are related to the flask framework so let's go ahead and build our first application in python okay so i have already opened my pycharm here and you can basically pay attention that i opened it in a directory that is the same directory that we created so make sure that you point your id to the directory that we created a few minutes ago and then inside our directory we are going to create our first python file and you can do that by that way in python so i will call it market and then once i have done that it is a great idea to bring in from the web browser the starter template to basically build up your first flask application now flask documentation already includes some basic structure that is going to allow us to build our first hello world application so let's go ahead and bring this in our screen and make that a little bigger and you can see here that inside that website we have a minimal application that is looking something like the following and i will allow myself to copy the entire code from here and paste this in our python so let's open our ide again and i will paste this here and let's see what is going on here so as the first line we can already see that we import the flask instance from the entire flask package so it is quite obvious and it is not surprising but then we can see that we initialize the instance of the flask with the given argument of double underscore name double underscore now if you never saw this variable before i have a video that is quite explaining what this magic variable is about basically this is a built-in variable that you can always call from any python file and it is referring to the local python file that you are working with so the flask instance is requiring to receive this parameter and this is why you are going to see that and don't worry too much about that if you don't understand it basically just leave it as it is and now we can see that in the fault line we have something that is called a decorator in python now a decorator is basically a one step before a function that is going to be executed now when you see here app.route it is basically saying that what url in your website i am going to navigate through and display you some html code so you can see that inside here we have an argument that is basically saying a full slash inside the string now this is the home page of your built-in website so if you just basically go ahead and type in some url without navigating for a specific page then it is going to lead you by default to that specific page so you can refer it as your root url of your website and then we can see that we have a function that is defined here and then it returns a string that says hello world now this is the exact place that we should see some html code in the future but for now we are only returning a basic string that is saying hello world and those in flask are trended to call routes or views sometimes people call it wheels because in django it is called views and django is another web framework of python but i will try to stick with one word when i'm going to refer to those functions that are routing to a specific page and we are going to call them routes so once we understand what is going on inside this startup template then it is a great idea to raise our terminal here and run in some commands to start this application so let me clean the screen here and in order to make our application run successfully we are required to set up several environment variables so i will go here and write up set flask app like this and make sure that all the letters are capitalized here and if you are working on a linux machine this command is basically should be export and not set so if you are on windows set will work and i'm going to make that to be equal to the same name of the python file that we have just created and if you remember we call this market dot pi and once we have set that then we can basically go ahead and execute our application by saying here flask run and once i have done that you can see that we receive several warnings that we are going to explain them in the future but that last line is quite important to understand so you can see that it says that it's running on http 127.001 and then we see a column here and then a number after that now if you know a little bit about basic networking then you can understand that this ip is a convention ip address that is basically referring to your local machine so this ip is going to be the same for each machine that this application is running on and we have something that is called the ports that are basically describing the application that you are hosting as numbers so for flask by default it will be 5000 so if i will copy this url from here and paste this in our web browser then we should see a message hello world and that is perfect because we were able to complete the entire starting process successfully in the flask web framework so we can basically go ahead and continue from here and one more point that i did not mention you'll see this hello world text because this is the root url of your web application and basically the hello world function that we saw before knows how to handle this so for example if i was to go here and type in slash about for example then we should receive an error that this is not found because we are not having a route that is handling the slash about so this is the reason we saw the hello world message properly okay so i'm back to my pycharm and let's actually go ahead and try to customize this string a little bit to return a better looking page so we can basically go inside the string that we are returning and type in here some html code that will basically be rendered in the page that we are displaying so we can go here and use the h1 tag which is basically the biggest header tag that is possible in html and we can write in here some text again like hello world but bigger and then we can go ahead and close our tag like this now if you don't know anything about html don't worry too much about that because most of the html code that i'm going to write here i'm going to explain what i'm going to do or i'm just basically going to copying and pasting several html code snippets so we can make our lives easier when we display nicer pages okay so let's go ahead and save this out and go back to our terminal and restart our server so i will stop the execution of our web server and type in again flask run and then we will go to our web browser again and basically navigate back to the root url so i will just hit enter here then we can see that we receive this message of hello rolled but bigger now you could see that in order to display this text i went ahead to my terminal and restarted our web application and you are probably asking yourself if this process is required to accomplish every time that you are changing your code well the answer for that is for sure no because you probably don't want to go ahead and restart your application every time that you are taking several changes within your project so in order to prevent such a behavior we should go back to our terminal and look up for something that is called debug mode right here now you can see that we are having the debug mode off and you want to turn it on basically because this will allow your application to being synchronized every time you change your code within your market.pi file so if i was to exit our web application that time and let's actually clean our screen again and we can basically go ahead and set up one more environment variable that will turn the debug mode on and that will be by the set command again and i will set the flask on the scar debug to one so basically this turns on the debug mode and then i will allow myself to run flask run again and then now that time we can see that the debug mode is on now let's go to our python again and change the string that we are returning on our root url and see if those changes will be synchronized without restarting our web server so i will go here and i will basically type in here change text something like that and i will go back to my web browser and refresh that out and then you can see that the changes have been affected without restarting our web server so we can test this one more time by adding some explanation marks here and save that out and go back to our web browser and refresh it and then you can see that the changes are being synchronized when you are on debug mode now the debug mode is something that you always want to turn on when you develop your application but once you go ahead and deploy this application in production then you definitely don't want to turn the debug mode on because this will cause the clients that are basically surfing on that web server to see errors of your web application and it is always not nice to see your bugs as the one who uses your services so make sure that if you deploy your web application in the future then prevent the debug mode on because this is very important okay so let's see what else we can do with our routes here so let's actually revert this back to hello world again and i will basically create here one more route just to practice how routes are working because we are going to create a lot of them in the future so i will write here the decorator that is required to make the route to understand which url you want to enable in your web application so i will go ahead here and type in slash about and then once i have done that you should go ahead and create your function that will handle all the requests that are arriving to this url which is slash about and i will call this function about underscore page and i will close this out and i will go ahead and return one more html string here that will say about page so as you paid attention i created those h1 tags again and just to test this off in that stage let's go ahead to our web browser again and try to navigate through slash about and this time you could guess that the slash about is going to work because we are handling what the slash about supposed to do so i just wanted to show you that you can create as much as routes as you want and then you can basically return some html response to your web pages now sometimes you don't always want to go ahead and hard coding your routes like we did until now so if you imagine a situation like in facebook where you have different urls for like millions of profiles then you probably can understand that the facebook developers are not going ahead and creating millions of routes by hard coding their profile names so besides that we can accept something that is called dynamic routes and what i mean by that is that basically you can go ahead to your route in your flask application and receive a variable name that is going to be accepted as well so let's imagine a situation that we want to display an about page for different people so let's go here and type in one more forward slash and then basically call the tags and add in here username now what i have done by this is basically i allowed this route to receive any string that we want after the about page and since i have done that i can go here and change this return to something else so let's go here and write in a formatted string and i will open this h1 tags again and i will close it like this and then between those i will go ahead and type in this is the about page of and then let's call here the user name that we receive here now you can pay attention that this returns us an error because we should handle this variable inside our function as well so let's accept this as a parameter so i will go here and type in username and now i can basically go back to our web browser and check out if this works properly so i will go back to our web browser again and i will type in here forward slash and then let's give a random name like john and then you can see that we receive a page so we see the message here of this is the about page of john and i could go here and change this to whatever i want i can change it to michael to jim and to more names if i'd like to so the important point here is to understand the behavior of dynamic routes so just make sure that you understand the behavior of that as well okay so as you could notice here i deleted the about route from the last episode because i want to focus on the next topic that i am going to talk about just now so until now we raised our html text within our routes in a hard coded text like you see here now when we go ahead and design complex html pages you probably want to avoid storing long strings within only a single file so in order to overcome this we have a convention in flask to a way we can achieve such a task and the way we can basically do this is by creating a new directory that is called templates and then inside the templates directory we will start creating our html files and then we will separate our html code within this directory and we will refer our routes to those different html files so let's go ahead and get started and see how we can do this okay so i will start by creating a new directory here and you can see that i'm creating that inside our flask market project so it is very important and you want to name it templates so make sure that you don't give it another name like html pages or something else just basically go with templates because the templates name is actually a convention to a flask so the package can understand that you are going to locate there some html files and within our templates directory we will go ahead and create one more file and you can directly select the html file if you use the pycharm so i will name it home and then you can see that it already returns us some default html code and just for now i'm going to delete what is inside here and let's make our font bigger so we can understand what we are going to type in here just in a second now again for a basic example and to understand the process of referring a route to an html file we will basically go ahead here and type in hello i mean home page it might be a better way to do that so we will call it home page and basically i will save this file and go back to our market dot py and then besides returning the hard-coded string like we did previously we want to look for a way to point this route to the home.html that we have just created so it basically makes more sense to change this route a little bit and let's do that okay and let's go ahead and call this home page and then we will close this out and then write a column here and then we will return render underscore template now you could already pay attention that this returns us an error because we did not import it so we have to realize that we are going to import a lot of built-in functions that are inside the flask package so one of them will be render template and the render template knows how to handle your requests and basically direct them into html files so let's go ahead here to our first line and import here one more function from our flask package and it will be render underscore template and as i have done that i have to specify here one more argument and for sure this will be the name of our html file so i will go here and type in home.html and once i have done that let's go to our terminal and make sure that our server is still running and it is so let's go to our web browser and navigate to our root url and then you can see that we have completed the render template function successfully so this is the proper way that you always want to work when you organize your flask projects you always want to create that directory that is called templates and then you want to start storing your html files in this specific directory okay so now that we understood how we can refer our routes into different html files it is about time to start working on styling our pages so our application could start be looking like a real website so in order to start styling we probably want to import one of the styling frameworks that are already existing out there so the most popular styling framework will be a styling framework that is called bootstrap and you may have heard about bootstrap already because this is the most popular framework to style your pages and the main reason that you want to use a ready styling framework is to save time by the process of styling each of our html elements because we really want to focus on the python side of our web application so you can import the bootstrap styling by going ahead to your web browser and basically searching bootstrap starter template and this starter template will help you to get started with all the requirements that are necessary to style your web pages so let's actually go into getbootstrap.com like i have already done here and go to that docs 4.5 so this is right here is the version of bootstrap so you want to make sure that you use the same version as i do currently because this might lead to differences if you just work with another version so just make sure to work with 4.5 as well so i will allow myself to copy the entire html code from here and paste this in into our home.html that we have just created so i will open back our pycharm again and i will go inside our home.html and i will paste this over here now i know that it is a lot of html code to sync in but i'm going to go over each of the lines once so we can really understand how an html structure looks like so let's go to the first line here and make our phone a little bit smaller so we can see most of the parts of this file alright so at the top here at the very first two lines we have some lines that should be located in each html file so basically this specifies that this document is going to be within a type of html and the language that we are going to use is going to be english so this is why we see the e and n letters now each html file is divided into two important sections or what is so called html tags and those sections are called head and body now inside a head tag you are probably going to see a lot of things that are pretty much meta information or some imports that is pulling the styling and also some necessary information to change your tab name when you navigate for that specific page so for example if we see here inside our head tag another html tag that is called title so this should be our name of the tab that we currently looking on so i will show the result of this html file just in a second and we can verify that the tab name is going to be hello comma road so one more important line inside our head tag will be this line over here so you don't want to touch it at all because this is what importing the entire styling for our home.html file so you can basically see that by the link tag and the href attribute is the url that is probably pointing to that complex styling so this is something that is called css and the css allows pages to look a lot better and more dynamic so it is important to leave those lines over here okay so i will allow myself to close the head tag and let's talk about the body now the body tag is what is really important and what really matters when you want to display some information within your pages now you can see that we also have here the h1 tag that we used previously and you can see that its text is hello world as well and you know what let's actually go ahead and change this to home page so we can have a better understanding of how this is going to be look like now when you see the tag explanation mark and then the dashes two times it is basically saying that the following line is going to be a comment now you can already understand that because this is uncolored in pycharm so this is basically a comment and down here you can see two more tags that are called script now when you see script tags those are javascript libraries that are also going to be important and this is also a huge part when you design a webpage so you also don't want to touch that because it deals with all the functionality within our pages so you don't want to touch those script tags as well so just make sure to keep them in your file and you can also see that we have one more long comment here but you can see that we have script tags within those comments so what that means it means that we can go ahead in the future and uncomment those lines so we can make use of more javascript libraries but i will leave it now as it is okay so now we understood the structure of a basic html file let's go back to our web browser again and see the results of this page so i will go here and close this starter template and refresh our page then you can see that already the font of our page has been changed now i noticed that i zoomed in much in this page so i will basically revert this back okay so you can see that the font has been already changed and this is what bootstrap is responsible for so when we go ahead and add more html code you are probably going to see that in a nicer way because of this bootstrap starter template that we already imported now you can also see here that our tab name is hello comma world as we have said a few minutes ago so this is also something nice that we can control by ourselves and we will for sure do that in the future okay so i think this will be it about the explanation of how html page is looking like so as i said before i really want to keep on decreasing my explanations about each of the html lines that i'm going to write in so we will have a better focus on the python side of this flask application but for sure if you have any questions about the html in general make sure to comment them out so i can read them off and respond you all right so let's go back to our market dot py and take care of something that is quite bothering me until now now you can see that our homepage is basically rendered when we went ahead and did not specify any extra information after our ip address and our poll now in most of the websites if you go ahead and type in slash home here basically this will be responsible to render you the same result like we saw previously now in order to handle two routes for a single html file it is as easy as going down to our pycharm and right in here one more decorator so it will be app dot route and then this time we will write here slash home and if we want to test this out we can basically refresh our page and then you can see that we see the same result like previously and if i delete everything from here the result is going to be same so this is something that you want to keep on your web pages because it makes sense to display the home page in both of the cases okay so now that we have understand how we can design our pages nicer it is about time to give our page a little bit nicer style rather than displaying a home page so we will start by adding a navigation bar so our users could have the option to navigate through different pages so the page that i will bring in here will be my personal website and throughout this video or in the future episodes i am going to go into my personal website a lot and copying some html code snippets that will help us to write html a little bit faster so i'm going to include a lot of html code snippets throughout this tutorial so just make sure to go to the description of that video and navigate through the url that is going to be specified as the code snippets url and get those code snippets so it will be much easier to you to follow this video so for this example to add a navigation bar i will go here and select the second part of this tutorial and i will basically go and navigate for our code and then you can see that as the first code snippet i have here the code snippet of navbar so i will allow myself to copy everything here and paste this in just under our body tag so let's fix the indentation here and paste this in and now we should see a nice navigation bar inside our homepage so let's fix the indentation here a little bit more so we can have a better understanding which tag is inside another tag so i'm just going to fix that and i think that will be enough okay so what let's delete those indentations and now i think we are fine okay so now i will save this up and go to our website and refresh that out and then you can see that we have this nice navigation bar up top here and then you can see that we have its name which is called gymshade coding market now we can change this whatever text we want we just need to find this specific html tag that is responsible to display this text so let's actually go ahead and find it so we can have a better practice of how we can find specific html tags so i see that we have this text here and i can basically go ahead and change this to flask market and if i save this up and refresh it you can see that the changes are affected now you can see that we have this navigation bar but we don't have any extra links that we can click on them and actually navigate through different pages so to add those links we have to go to our python and basically add some optional links so that the user can see which pages he can navigate so to ease on that process i can also go to my website i mean to my original website and then copy the second code snippet here which is called navbar dash options i mean underscore so let's go back to our pycharm and we want to paste this in right here where we see a div tag which is with a class that is named as collapsed navbar collapse okay so we will paste this in over here and once we do that then we should see a better result of the items that should be available inside our navigation bar so if we go to our website and refresh that out then we can already see a better result of how a real navigation bar looks like and we can see that we have home market and we have login and register now for sure when i go ahead and click on them it should not lead us to any different page because we did not configure those routes yet and we will do them in the near future now just to have a better understanding what is going on inside the second code snippet that we have just copied and pasted you can see that we have some li tags over here and this is a shortened version of a list tag so you can see that each one of them just responsible to display some item that is available inside our navigation bar so we have here this which is basically a link to our home and we have that one which is going to be the link for the market in the future and as you could pay attention we have in the right side the login and register which we will configure in the future as well okay so one more customization that i want to apply for this home page is to return it into a dark mode now in order to allow the page to be in dark mode basically you have to override some styling attributes and then your page will be displayed in a background color of black and all the text that you are going to provide are going to be displayed as white colors so in order to accomplish that i'm going to navigate down in this home.html file and let's make our font a little bit bigger here so you can have a better look and right after our closure of the body tag i'm going to open up a new tag that is named style and i will close this up and between those i am going to provide some extra attributes that will override the attributes of our entire body so it will be something like the following so we will start by typing in body and then we will open and close curly brackets and press enter here so we can enter inside our brackets and then here we will override the two attributes and the first one will be background dash color and i'm going to add here a column sign as well and this will be equal to a hexadecimal value that i already know that it is going to display a back color so if you don't know what an hexadecimal value is it is basically another way to define colors rather than just text so this is pretty much equal to writing here black inside a string but this is going to make it a little bit more close to gray rather than just black so this is why i defined it with an hexadecimal value now in order to close this attribute we should add a semicolon here and our second attribute that we want to override will be color and that time i will give it as a pure text so it will be white now once i go ahead and save this file and go back to our page and refresh that out then you can see that our page is turned into dark mode so make sure that you apply those configurations as well in your home.html file in order to turn your website into a cool looking dark mode and i just realized that our tab name over here is still hello world so let's go ahead and change this to finalize our styling so i will go back to our pycharm and let's find this title tag that is responsible to display the tab name so i will expand our head tag back and we should change this into something that they are currently in the homepage so let's change this to homepage and remove the explanation mark and let's separate those words here and save that out and if we go ahead and refresh this then you can see that our tab name is changed so i think that will be it for the styling part of our website and in the future for sure we will add some extra elements to make our site even nicer alright so now it makes sense to start working on some new python code to deliver a new items page to our users so this is why i will be starting to create here a new route and we will render a new html template so let's go ahead and do this so i will jump to a new line here and we will start creating a new route so i will call the app dot route decorator here and it quite makes sense to send our users to a url that is looking like slash market so i will write it like this and i will continue on and create our function and we will name it market page and currently we will receive nothing as parameters and we will go ahead here and return vendor template and we will send them to a new html file that is called market.html now i know that we did not create this yet so let's go ahead and do this so as you remember previously we just went inside our templates directory and we created an html file and we should name it market so this route could understand where we should send our users so let's go ahead and name this market and if you use pycharm then you will receive this auto-generated html now to make our lives easier a little bit i'm going to copy everything from the home.html and i'm going to customize it a little bit so we can understand that we are inside the market page and not inside the home page so i will go to our home page here and i will grab everything that is inside the home.html and i will paste this in inside our market page and let's make the font a little bit bigger here now several changes that it might be a great idea to done here is for sure this title tag that is changing the tab name so let's change this to market and i will scroll down here let's minimize this navbar and we will change this home page h1 tag to market page so we can understand where we are currently at now for myself here the website is currently not running so let's go ahead and complete the steps that we are required to run our website quickly so set flask app equals to market dot py and we also have to set the flask underscore debug to one and now we are ready to go ahead and execute flask run and as we have completed this let's go to our web browser and try to navigate through the slash market route that we have just created and we can see that the results are quite great so now we are ready to work on to see how we can send information to this html from our route now to do this i am basically going to go back to my pycharm and we are going to work on the route of market that we have created and we will try to send some random data from this route to our html and see how we can access it now the way we can do this is as easy as going here and sending more arguments that we will be accessing by their keys so let's go ahead and see an example for that so let's write in here item underscore name equals to phone and i will close the parameters here back again and let's make this to be in the pip 8 style and now the way that we can access this is by this key name item underscore name now it makes sense to go back to our market page now and see how we can see the value of the item name argument so i will go to our market and actually to access that information we have to start using some new web templating engine that is called jinja template now this might be sound weird what i'm saying now but if you remember when we went ahead and installed the flask library we kind of saw a lot of secondary libraries that the flask library is required to have them and one of those libraries are actually named jinja now as i said jinja is a special web templating syntax that we are able to access through html because it is specially designed for python web frameworks so to do this i am going to go here and let's open here a new html tag for example a p tag so it will be a new paragraph and the way we can access this is by calling the variable syntax and that will be by double curly brackets opening and closing like the following now as i have set those curly brackets here we are allowed to access the information that we have sent from our route and as you remember we have sent the key value of item underscore name so if i was to go inside our curly brackets and type in here item underscore name then we should see the value of this variable on our page so to test this out i will go to my web browser and refresh it and then you can see that we see the value of the item underscore name so this is a quite great achievement and i hope that you understood all the process of how we can display information from our routes because to be honest when i saw the ginger syntax first i really was shocked and did not understand anything but i hope that this was a clear explanation and that you understand correctly why we have to include ginger syntax in our html templates so i will go back to our html file here and continue from here okay so as you see i'm back on my market.py file and now we have to look forward to how we can display multiple items on our website now to do this we can basically change the value that we send to a list now i already have some information that i already generated up and this is basically a list of dictionaries so we will be able to display better data on our website when it comes to displaying some random items so to bring this code snippet that i already have generated up let's go to my website again and navigate through the third part of this flask series and bring these items list of dictionaries called snippet now as you can see we are only having a long list with three dictionaries here so let's copy this up and paste this inside our market page now let's have a quick look in this long list here basically what we are having is three dictionaries that they are happening to have the same keys so we have id for this and this and that and also the name key and as well as barcode and a price now once i have copied this out it might be a better idea to change our send information in this renderer template and i will basically delete this item underscore name equals to phone and i will change this up to items equals to items so now we will be able to access this entire list of items with calling the variable of items because this is what we have named over here now to test this out again we can basically go to our market.html and change this to items so if we save our file and refresh our website then you can see that we see this exact dictionary i mean the list of dictionaries over here now you can pay attention that this looks quite ugly so to style this up i am going to insert these values inside a nice designed bootstrap table so let's go ahead and do this all right so we will go back to our market.html file and in here we will just delete this paragraph for now and we have to use an html tag that is named table and inside here i have to provide some information regarding to my tables rows and columns and to save this work from us i already have generated a table that is going to look quite nice and we are going to add to it some extra information to design our rows and columns so to bring this code snippet here we will go to my website here and we will bring this bootstrap table code snippet from the third part so i will get this html code snippet and here i will just replace this with those table tags so if we copy this then we can see that we have here the table tag again but we have an attribute that we did not talk about it before basically when you see the class attribute inside an html file it basically refers to bootstrap classes that their main goal is to give a nicer design to your specific html templates so for example if we see a class that is named table hover then we should see a special effect when we bring our mouse and hover inside our table and if we see table dark then you can probably understand that this table is going to be in dark design so in here we have our table head and table body and as you can see i already commented here that we have to create certain columns here now since our dictionary includes some more than one key values then it might be a great idea to create more columns to our table so this is why i will go down here and i will start copying and pasting this code snippet three more times and i will replace those by the values of the keys that we have inside our dictionaries so if you remember we had a dictionary with a key of name and we had an id so i did not touch this column at all and i'm going to change this to barcode and i'm going to write here price as well so as we have done that the way that we can fill in rows to our table will be easily by going down to the table body and writing some extra information inside those table row tags so tr is a shortened version of table row now as you can see we have here some more tag that is called table data and this is basically a reference to the first column that you see here so if we are happened to copy this out and paste this in then since this is the second table data inside this table row then this is going to be located right under the column of name so this is why it is a great idea to change this to value for name and i'm going to repeat this two more times so this will be barcode and this will be um price okay so as we have done that let's test the results inside our website so i will go to my web browser and we will navigate through our market page and refresh that out and you can see that we see here a nice table and you can see that those are the headers as you can pay attention that its color is a little bit more bold and we can see that we have here information that is inside our table so it is quite great achievement okay so now that we have done this we still don't display the real information that we have sent from our market page route so let's bring up this for a second to remember this so i will open back our pycharm and i will go to market.py for a second so if you remember we sent this items list towards our market.html but we did not display the actual values of those dictionaries that are inside the items list so to do this we have to iterate over this items list over here and once we iterate over this list then we have to access each of those keys in some way so let's see how we can do this okay so let's go back to our market dot html well i'm not going to touch the html code inside our table head because in table head we done a great job because we only want to display here the columns names so i'm not going to touch it at all so let's minimize the table head for a second and now as you paid attention each of our tr tags are responsible to create a new row inside our table so it might make sense to start to launch here a for loop and start iterating over our items but how we are going to do this with the ginger template so if you remember the ginger template is that special template that allows us to access the information that arrives from the route so i'm going to write here new ginger syntax that we did not see so besides doing curly brackets twice i am going to replace the inner curly brackets with percentage signs and what that means it means that you are going to call a logic code so if until now we were able to access variables that are arriving from ginger syntax this time when you see the percentage signs basically you can write a code that is quite looking like a python code but this time it is not going to be variable names and stuff like that besides those are going to be if statements for loops and stuff related to actual logic so in here i can go with four item in items now the reason i write here items because this is accessible from the market route and to close our for loop here i will call those code blocks once again and i will right here and four together combined so this is the exact syntax of how you can bring in a for loop inside your html template and now i'm going to cut this entire tr html block here and i'm going to paste this in inside this for loop that we have just created so once we paste this in let's organize the indentation for a second great so now we should see this table row three times and the reason we should see this three times because we have three dictionaries in our items list so if we save this and go here and refresh that out then this is the exact result that i was talking about so again the reason we see this three times because we have three dictionaries inside our items list okay so our next problem is quite clear and the problem is that we don't see the values yet although we iterate over this items list so to access each of the keys that are inside those dictionaries we can basically go and open our pycharm back and replace those strings here that are inside the html tags with the actual value so to do this i can basically delete this up and call the variable block again by typing in curly brackets twice and i can basically type in here item dot id now the id is the key name of the dictionary and the item is the variable that i'm iterating on so this is why i can access this item variable and i can change all those three table datas here to the same as this one so let's go ahead and do this so i will replace this with item dot name and i will replace this with item dot barcode and i can replace this for sure weight item dot barcode and we will close our curly brackets and create a space here so sorry this should be price okay so we should change this to price and now we can go to our html page again and refresh it then you can see the actual information that we meant to display from the real beginning okay so this is great achievement so if we are happened to add some more information inside our market.py then this page is for sure going to be updated automatically so one more final thing here to customize this page a little bit better we can add here a dollar sign or something that the customer that uses this website could understand that we are referring to actual money so we can basically go back here and add here the dollar sign and see the effect of that over here all right so one more final thing that i'd like to do in this table is enabling our users the options of seeing more information regarding to a specific item and also the option of purchasing a specific item because we actually want to simulate a situation where we have items in market so to do this we can basically create one more column here and we can name it options and we can add two more buttons in each of our item rows so let's go ahead to pycharm and do this so i will open my pycharm here and i will find the table that we have created so as you remember our columns are located inside an html tag that is called t head so we will expand this back and we will add here one more column so we will create a th tag and our scope will be col so this is a shortened version of column and here we will add options and so we added the column here and now we have to add its value in each of our rows so to do this we can basically go here to our table body and find our for loop and add here one more td tag which is table data and over here i will basically hit enter so we can add more html elements and i will call the button element to display a nice looking button to show our users the options that he can do so let's create here the button tag and over here i want to customize this button a little bit so i will call the class attribute and inside the strings here i will specify the classes so i will write in here several classes that i already know that they are going to customize this button a little bit better so we will write here button like this and we will also write button dash outline and we will also write here button dash info now again those classes are made for specialize our styling in each of our html tags so let's go ahead and close our button tag and you can see that we already have the closure for this button and so now i want to write here a text like more info and i want to scroll down a bit so you can see what i am doing here and so now that we have completed this button basically i want to repeat the same process to allowing our users to purchase that specific item so it will be the button tag again and this time our classes are going to be again to btn and button dash outline and that time i will type in here button dash success so the differences between button dash info to button dash success the button info is going to fade into our button a more blue color and the button success will fade in the green color so when i go ahead and close those tags i can basically write in here purchase this item now let's go ahead and test this out so i will open my browser again and i will refresh our page and you can see that we receive the options right here so this is quite great now for sure if i click on one of those buttons nothing is going to happen because we did not configure the functionality behind those buttons but we will do this in the future so don't worry about it right now alright so previously we were able to display a nice looking market page by writing this html code and it was responsible to display a nice looking page with several items now if you remember to display this nice looking page i went for my home.html and i copied the entire code from here and i pasted in inside mymarket.html and then later on we gave it our own customizations now if we consider a situation that our website could be divided into 10 or 20 different pages that will mean that we have to copy and paste some basic html code every time that we want to come up with a new page and the reason is we want to keep certain elements in each page that we display so for example if you see in the home.html we happen to have this long nav html tag now it is obvious that we want to display the navigation bar in each page that our users navigate on because we want to allow our users to see the pages that they can navigate so the main point here is to think about some method that will avoid copying and pasting a lot of html code and to overcome this we have something that is called template inheritance now the idea behind that will be to have one base template html that we will always inherit from and that way we will save a lot of copying and pasting html code so in order to achieve this what we have to do is creating one more html template and it makes sense to give it a name like base layout template whatever you like to and then basically put in there some html code that will be always displayed to our users so let's go ahead and do this okay let's go inside our template directory and create an html file that we will name it base so let's go here and select new html file and i will call it base as i said and i will delete everything from the auto generated html now as you could guess i already came up with a base dot html that is going to save us a lot of time from writing some base template html now in order to get that base.html we will basically go to my website and bring it on here so we will go to the fourth part of this entire tutorial which is happen to be right there and we will select the code and bring in the base.html and for sure once i paste it i will go over what is going on here so we have our base template and in the next few minutes we are going to show how we can inherit the entire html code from this base template now let's see what is going on inside the head tag now in the head tag we have the same tags that we were happened to copy previously in this tutorial from the bootstrap starter template so there's nothing really different in here only what i have done here is named our title base title so we can see the effects of it now if we close up our head tag and focus on what is inside the body then we can see that i already have commented out the location where we want to see the navigation bar and also i also wrote here one more comment for the future contents that we are going to add to this base template so that way we can understand where we have to insert different html templates now down here again we see some javascript libraries that we import like we saw previously and this style here is again here to allow our site to be in dark mode so if you paid attention then we see that background color inside the body and we also see the color which is the foreground color as white so let's also close our style tank over here now once we understood what is going on inside our base.html it is a great idea to go inside our home.html and try to inherit whatever is inside this base.html that we have just created so in order to ease our lives here i will use the future of pycharm to split some html files into two or three different displays so let's go ahead and do this very quickly so i will click here split vertically and on our left pane we will keep our base.html and on our right pane we will display the home.html okay so now i will basically delete everything from the home.html and i will use some special ginger syntax to inherit the code that is inside the base.html so that will be by the code block syntax we saw previously so it will be curly brackets and then the percentage signs in that case and then we will use a function that is called extends so we are extending this base template and basically here inside our string we can specify the name of the html file that we want to extend from because all the html files are located in the same directory that we called templates so i will go here and write in base.html and once i have done that i should expect to see pretty much nothing in our home.html so let's go ahead and see this in action so i will go to our website and i will basically navigate for our home page and then you can see that we are happen to have this black page so now that we achieve this basically now we can decide which content we want to put inside base.html and which content we want our inside home.html so for example our long navigation bar html tags are must located inside our base.html so let's go ahead and do that so i will go to our pycharm and let's actually bring this long nav tag from the market.html so i will locate our market.html over here so let's grab our navigation bar so that will be the entire tag that is called nav and i will copy that out and i will paste it in where we located this command which is says navbar here so once i paste this then we should see a great result where our base template is having the navigation bar so let me customize the indentation a little bit and i think this looks okay so we will go to our website again and we will refresh that out and then you can see that our navigation bar is back up again now the beauty in that process is that no matter which html file i'm going to create in the future all i have to do is using this extends method that we saw just a minute ago and then each time i do this then we will see our navigation bar so this is a quite great achievement okay so even though we have completed the inheritance successfully there are still some problems left that we have to understand how we can figure out for example one of them will be the fact that you see that our tab name is base title now we are inside our home page so it does not make sense to display to our users base title each time so what i mean by that is that we have to figure out how we can differentiate between content that we want to display up on our each page to a content that is going to be unique per page so let's go ahead and do this so i will open my pycharm here and basically on the left pane we got our base template and on the right pane the home.html again and now what i can do is basically marking any area in our template that is going to be unique per page so the way i can do that is as easy as going for example inside our title tag and write in here some special ginger syntax so it will be by using the brackets and then the percentage sign and then we have to use the function that is called block so i will use this function and i will give it a name like title and i will close our block by using and block now if what i have done until now is quite weird for you i can totally understand that but you will get that in a few minutes so once i have done this then i am allowed to go inside our home.html and call this block of code by simply writing block title and then inside here i can write anything that i want and the content that i'm going to put in right after our blog title is going to be replaced and use the content that we write in home page so let's see that in action so i will right here and block again just to close our block and then inside here let's write a text like home page and use the indentation here so it will give it a cleaner look and once i have done that we can basically save this and go to our website again and once i refresh it then you can see that our tab name is changed to home page so the ability to mark certain areas in our base template as unique per page areas is quite great because it is going to allow us to write more organized code and now basically we can use this block functions in more areas inside our base dot html and then we can call those blocks in our different pages inside our project so i will go to our python and declare here one more area that is going to be as the area of our body in each page so we can basically go here and use the block again and now we can name it something like content so let's fix our indentation here like that and then we can write again and block and once i have done that we can basically go back to our home.html and try to call this content block again and write whatever that we want to write to display it inside our homepage so i'm going to go back to my home.html again and i'm going to use the block content and then i will close our block by simply saying end block and now we can write a text like this is our content for the home page and once i save this then we should see the this is our content for the home page only in our home page so let's test this out so once i refresh that out then you can see that we see this text right here all right so now that we have applied the inheritance correctly for our homepage let's also do this for our items page so we will basically go to our market.html and take the same actions over there so i will open my pycharm in market.html and before i actually go ahead and delete everything from here it is a great idea to copy the table that we have created previously and then later on we will paste it inside our blog content block so let's go ahead and do that okay so i will navigate down here and i will find our table and you can see that it is right here and then i will find the closure of this tag and i will grab the entire table and i will basically copy this entire html snippet and now i am pretty much ready to delete everything from here and using the methods that we have applied for our home.html so i will start by writing extends base dot html and i will continue on here as using the blog title and the block and the end block again and then we should do the same process for block content so it will be block content and again we have to close our block once again so once i have done that basically inside our title we just have to give it a text like market page and inside our content it is a great idea to paste our table back in so we can have pretty much the same page that we had previously so i will go in here and then create an indentation a little bit and then paste back our table so i think this should work let's test this out by going to chrome again and refresh our homepage and then you can see that the behavior is quite same now i will navigate also to our market and then you can see that we still get pretty much the same result like we have done previously what we can do is basically adding a title like market page and we will just continue with the customizations in the future so this is a pretty much great results until now and i hope that the entire process of how we can use the template inheritance was pretty much clear for you okay so there are still customizations left before we close this template inheritance topic and basically inside our navigation bar we currently don't have the functionality to navigate between different pages so to test this up if i click on home page nothing happens and as well as in our market over here so let's go ahead and configure them so i will open our pycharm again and we will open our base template and inside our navigation bar we can basically look up for those a tags now those a tags are what responsible to navigate users to different pages and so if you look at the href attribute inside the a tags this is what is actually sending our users to different areas now we could have done here something like slash home so in that case it will navigate our users to slash home but this is not a great idea because you don't want to hard code your urls in that way so what happens if in one day you want to change the route to something else then it is not considered as a best practice now again this is going to work i'm not saying that it is not going to work but it is quite wrong and we can even check this out if it works properly so we can go to here and refresh our page and click on home and then this will basically navigate our users to home page but we can do this in a more pretty way and i like to apply that okay so i'll open back our pycharm and in here besides hard coding for slash home we can basically use a built-in function from the ginger syntax that is going to look like url underscore four so let's call this up in here and pay attention that i use the double curly brackets so in here i can close this function like that and between here the url underscore 4 expects for one special argument now the argument that we are going to give for that function will be the value of the name of our route that we want to navigate our users so in this case if we want to navigate our users to the home page then we should type in here the name of our route that we have created to navigate our users to the home page and in our case if you remember our route name was home underscore page so we can basically go here and type in home underscore page and once i save this let's go to our web page and test this out so i will basically navigate back to market and i will click on the home page and then you can see that it knows automatically to navigate our users to forward slash home now this would even work if i was to go inside our market dot py and change this to something else like home three times okay let's just do this for testing reasons and test that out so i will go to market again and try to navigate back to our home page then you can see that now we were able to achieve a kind of a dynamic way to navigate our users to the home page so we only have to specify the name of our functions rather than specifying the hard-coded urls so of course i'm not going to leave this home home home so let's revert this back and i will delete this from here and that will be it so let's apply the same thing for the market url as well so i will basically copy everything from here and i will paste it in inside our href where the market is located and since our function name was market page then i will basically change this to market underscore page and once i have done that let's test the results one final time so for sure now if i refresh then our flask could not find anything that is related to home home home so we will write in here home back and click on market then you can see that the behavior is quite great so the url 4 is quite useful in that case okay so just a quick reminder here this is the final situation that we have reached until now on our website so if you remember those items that you see on the slash market page was basically because of the list of dictionaries that is arriving from here and is sent directly to our template and now we want to look for a way to change this behavior so we will be able to store information inside an organized database so the way we are going to do that is by configuring several configurations on our flask application and we are basically going to use a real database that is going to store our information inside tables now if you never worked with databases before basically it allows you to store organized information within tables where each table describes some data that you want to store so for example you may have a table that its name is item and it may have a columns such as name barcode and price and this is exactly what we are going to do in order to store organized information inside an organized database so just a quick brief for the way that we are going to implement this basically we are going to use a new file and that file is going to store all our information now normally when you want to store a large amount of information you should execute a database service that is running in the background of your machine but we are not going to do that because we are only working on a local environment and currently we don't have any case where a lot of users are going to cause traffic on our website so this is why we can allow ourselves to use a minimal database and we can store our information inside a file besides running a database service on our machine so the way we are going to do this is by using sqlite3 so sqlite3 is an extension of a file that allows to store information and we are going to connect that file to our flask application so let's go ahead and do that okay so first of first we need a flask tool that allows to create tables within that database that we are going to work with with using python code now when it comes to developing websites with python basically you can create your database tables with python classes so in order to use this feature we need to go ahead and install some flask tool that allows us to do so so we will basically go ahead to our terminal and stop our website for a second so we will basically go ahead and write in pip install flask dash sql alchemy now this is the exact package that will allow us to write database tables with python classes and we are going to see how we are going to do the conversion from python to actual database information just in a few minutes so let's go ahead and install that and once i click in here then we can see that we receive a successfully installed flask alchemy message and if you do not receive any errors here then you should be fine now let's clean our screen here just a minute okay so now we can go basically back to our pycharm and continue on with the configurations that we should apply okay so once we install it we can basically go ahead and import that flask underscore sql alchemy so let's make our phone a little bit bigger here and we will basically say from flask underscore sql alchemy import sql alchemy like that and once we have done that basically we can go ahead and create an instance of that class that we have imported now the convention here would be to call that variable db because this is going to be our database instance and we are going to rely on that in the future so we will type in here db equals to sql alchemy and we will close parenthesis to initialize an instance of that class and once we have done that we need to pass our application as an argument to that sql alchemy class so we will basically type in here at and if you remember that arrives from here where we created a flask instance so it is important to complete that line by writing in here app now once we have done that basically we can start creating our own classes and later on they will be converted into database table now those special classes that are going to be converted in the future to database table are called models so we are going to create one module that its name is going to be item and we are going to define several columns that are going to be inside our database in the future so just basically let's go ahead and see what i said with a python code so we will go down here a few lines and we will create here a new class and we will name it item and once i have done that basically i should import from a special class that is going to say to our flask application that this is a model that is going to be table inside our database so this is why i will open up a parenthesis here and i will inherit from a class that is called db dot model so we will basically start by creating some fields and we will start by creating a field that its name is going to be named because it quite makes sense to describe our items with a name so we will go ahead and type in here name equals to and the way we are going to create a column will be by db.com and you want to close the parentheses so we can understand that we are creating an instance of this column class and once i create this then we should pass in here some extra information in order to create this column successfully now one of them will be the type of the column that you want to create so we want to make it in string type so this is why i will go ahead and type in your db dot string and i will close the parenthesis here as well now inside the string we can basically limit the amount of characters that we should put in each of our names so i can limit it to 30 characters by basically typing in here length equals to 30. so when i go ahead and do this basically i am not allowed to create an item instance and describe a name with more than 30 characters and this is something that you want to do because you probably want to avoid the situation where you allow your users to create items with a large amount of characters because this could cause from database to store too much information and you probably don't want to do that so 30 characters for a name should be enough okay so once i have done that i can basically go outside of our string class in here and pass in here some more arguments right there so one of the first arguments that we want to pass is to describe to that column that we don't want to have null fields so we can go ahead and do that by passing in here nullable equals to false and the next argument that i'm going to specify here is going to allow our names to not have the same name when it comes to storing a large amount of items so you probably want to avoid the situation where you have two or more items that their name are iphone 10 for example so you want each item name to be unique and you can do that by easily saying unique equals to true now if you remember we also had some more fields that are describing our items in this website so if you remember from the dummy information that we have generated from that list we also had barcode price and also id so let's go ahead and create those columns as well so i will basically go in here and create price equals to db dot column and that time we want to change our type of column to db dot integer and this will allow our column to store integers and not strings like we did previously so now we don't have to pass in length for example because this is an integer and so we can also continue on by typing in here nullable equals to false and by the way if you never heard about the null keyword before basically this is just another way to say none so if you saw none from python then you should be fine to understand null as well because this is just quite the same okay so i will delete that from here and continue on creating some more fields now one more field will be the barcode that we also want to create so it will be db dot column and although it is going to contain some digits i still want to pass it in as strings because i'm not going to do any calculation with this barcode i'm just going to store 12 characters that they happen to be digits so i will go in here and create string and we will just pass in here length equals 12 so each barcode will be 12 characters and again we will type in nullable equals false and this should be unique as well so we will type in here unique equals to true like that and once i have done that i also want to add one more field that we did not see before and this is going to be like a paragraph that is describing what this item is about so it makes sense to go down here and type in description equals to db dot string excuse me db dot column and now we will pass in here db dot string and now we probably want to give a huge amount of length in here something like 1024 something like that just because we want to probably describe our items with a nice paragraph so once i have done that i can continue on to nullable equals false and we can create unique equals to true here as well but i am assuming that we are not going to have the same description for our items if their size are almost 1000 characters but again the best practice will be to create unique equals true and now i also want to create one more special field that is quite required when it comes to sql alchemy now the one more field that you want to create is called identifier and this is a type that is called primary key so this is just a convention column that you should create when you create your models when it comes to creating models with the flask framework so we will go ahead and do that as well and we will type in here id equals to db dot column and its type will be db dot integer and we will basically go ahead and type in here primary underscore key equals to true now if you not quite understand why i'm doing this basically this is a convention to our flask models so it can understand the unique objects that are going to be inside our items so it is a must thing that you should do when you create modules with flask okay so there are still some steps left to see that item table within a nice looking database and we need to add several configurations to our application in order the flask to recognize a database so the way that we can do that is by grabbing the app object and adding in some new configuration so it will be add dot config and basically this statement here is a dictionary that is going to accept some new key values from us so we will basically go ahead and pass in here some new key value and we can do that by typing in here sql alchemy underscore database underscore uri and then we will point it to where we are going to store our file which is going to be the database file so we can do that by referring this configuration to a sqlite 3 file so i will basically go ahead and type in here sqli3 and this is going to be like a url but not besides it is going to be uri and i will explain the differences just in a second so i will basically type in here sqli3 column slash and we should add two more four slashes here as well and once i have done that we will just give a name to our database file so it will be market dot db okay so i know this line might confuse everyone here so let's go ahead step by step to understand this so first of first we see this app flask equals to double underscore name that we have created in the very first steps so we use this app object and we add extra configuration so our flask application can recognize its database and the way you can do that is by adding key values that are considered as conventions so the flask application can understand where the database is located at so the convention will be to create a key that its name is sql alchemy underscore database underscore uri so uri stands for uniform resource identifier and this is different from url that you probably saw everywhere because this is not a link to a website this is why we see the l at the end of this statement this is an identifier that is just a file that is going to be identified as database and basically the way that flask application wants us to do it is by passing in here sqlite colon three four slashes and then just give a random name to the file that you're going to create okay so once we have configured this successfully then we should go ahead and execute some commands in order to create this actual file and then we can see it visible inside our project directory so i will open our terminal here and inside our command line we want to enter to python shell because we want to import the information from our market dot py file so i can basically go ahead and type in here python and make sure that you do that in the same directory as your project so you will not receive any errors so once i have done that basically i can import our market.py file like a python module so i will type in here import i mean from market because this is the name of our python file import db now the reason i want to import db it is basically because i want to take several actions within that db variable that we created previously now once i will execute this you might receive a warning about some of the features that are going to be disabled in the near future but don't worry too much about that this is not an error so you are totally fine if you see this output now i want to split our display a little bit just to see you the result of what happens when i run the following command so i will basically locate our terminal in here and we'll make it a little bit bigger like that and now i will go ahead and create our database now the way that we can do that is by saying to our shell to create all our tables that we have created inside that python file and if you remember our modules are what considered as database tables to our flask application so i will run here db dot create underscore all and if you do not receive any errors after this command then you should be totally fine now once i have executed this then you should see the market.db file right here inside our project directory so that means that we have created database successfully so this is quite great now currently our database is totally empty from information so we probably want to go ahead and create some items inside our database and the way we can do that is by accessing our database like python code so this is what exactly sq alchemy allows us to do so if by any chance you come from django world then you should understand that the sql alchemy is quite like the object relation mapper of django so this is why we work with the sql alchemy okay so let's go ahead and create some items in here so i will basically import the item model that we have created so it will be from market import item and once i do that then i can basically go ahead and create an item like that so let's create a variable and it will be equal to item one and this will be equal to the item class so we will initialize an item and we will pass in here name equals to phone let's call it iphone 10 like that and we will also pass in price so it will be 500 and we will also pass in some barcode so if you remember this is a string so i will just create some random numbers in here and we should have 12 characters so this is quite great and we should also pass in description and this will be equal to just let's pass in a short description now once i enter this then we should be fine now you probably have noticed that we did not pass in anything about the id over here and the reason we did not pass anything about the id it is because the fact that we passed in here primary key equals to true so if this item is happened to be our first item in our database then its id is going to be one and we are going to see that just in a second okay so let's go back to our shell here and once we have created an instance of item then we want to save our changes to our database so the way that we can do that is by going ahead and typing here db.session dot add and we should pass in here the argument of the object that we have created which is item one and the next line here will be db dot session dot commit and you should close the parenthesis here like that and this should do the job of saving information inside our database now to verify that you already have one item inside your database then you can basically run a command like the following and the correct command for that will be item.query.org and once i run that then we should see a result of one object that is located inside our database and let's actually show what happens if we create one more item and commit our changes to our database so we will just type in here item two equals to item and we will pass pretty much the same information like we did previously so it will be name equals to let's type in here laptop and price would be 600 and this time the description again will be just a short description like that and what else we got we have to pass in barcode so let's pass in some random 12 digits like that and again we can basically go ahead and add this object to our db session so it will be the following command and we can basically run here db.session.com so it will commit our changes and again now i can execute the item dot query dot all and this should display us two items now you may notice how the objects are defined as the model name space the identifying number that i talked about now this is something that you can actually override and you can give your own customization to the way that you want to see your items when you try to query them by the python shell so let's go ahead and see how we can do that okay so i'm back inside our pycharm and this is as easy as overriding a magic method that is called dunder or epr now if you don't know what dunder repr is then i have a video on that special magic method and basically you can check my channel out to see the thunder r apr video okay so besides returning the default option that we saw previously we can basically return a formatted string and it will be item and then we will just pass in here self dot name inside curly brackets just to refer to that variable okay so once i save my changes here then we should load our information again from the beginning so i will exit our shell here and i will enter it back but before i will clean our screen and i will type in here python and i will go here and write form market import db and as well as we will throw market import item and now if i'm executing the same command like before so it will be item.query.org then you can see the differences from the previous result as we see our objects that they are defined in a different way so this is quite great okay so i just cleaned my screen here to show some more examples now i'm going to show how you can iterate over all of your items for example so it will be four item in item dot query dot all because this is the exact statement that returns all of our objects and once i iterate over it then we can access each field like the fields that we have created within our item model so it will be for example item dot name and it can be also item.price and it also can be item dot description and as well as item dot id and also item dot barcode now once i hit enter here then we should see all of our results that being shown like here so just remember that you can access each of your fields like we defined them inside our model okay so if we want to filter our objects by some specific condition this is something that is quite possible as well so let's go ahead and show that but just before let's clean our screen here so we can have a better look like that okay so the way you can filter by some condition would be by item dot query dot filter underscore by now the underscore by is actually referring to some key value that you want to specify in between those parentheses now let's say that i want to filter by items that they that its price is 500 so it could be basically price equals to 500 and once i click enter then it returns us a base query object like that now the reason you see this it is basically because you may have more than one result by executing that command so to see the actual result of what this exact statement returns you then you should iterate over it so it will be full item in item dot query dot filter underscore by and again i will just type right in here price equals to 500 and once i do that then i am allowed to access each of our items that their price are 500 dollars so we can basically type in here item dot name and once i execute this then we can see that we only have one item that its price is 500 and its name is iphone 10. now again just remember that you will receive this result because the filter on the score by can return you more than one option that this condition is actually a true statement for those objects okay so now that we pretty much understood everything that is relating to modules and databases it makes totally sense to scroll down here and change this dummy information to something else now you could probably guess what i'm going to write besides this long list that we have created so it will be as easy as typing in here item dot query dot all because this will basically return all the object of items that we have stored inside our database so once i save this and go back to our shell here and let's actually exit from our python shell and execute our server so it will be set flask underscore app equals to market dot py and it will be also flask underscore debug equals to one and we can execute here flask run okay so in here as you remember those three items are used to be the information that we have passed in as a dummy information now if i refresh it then you can see that it is updated with the information that is stored inside our database and this is the behavior that we want to reach when we want to display some information inside our website so this is totally fine and it works correctly so this means that we have done a great job by creating a database that is connected to our web application okay so one final thing that i'd like to discuss about is the option to inspect your database in a visual graphical user interface now because we use sqlite 3 as our database engine then we can download a browser that knows how to display information when it is done by sqlite3 so basically you can go ahead and search in google for a db browser for sqlite and then you can see that it has a lot of options for any kind of operation system so if i'm clicking here for example then you can see that it has download links for mac os and as well as for windows applications but basically this is something that you'll maybe want to do because you want to really have an actual look for what is inside your database so since i'm using windows machine currently then i already have downloaded this software and then i'm going to display you how you can browse your information in a visual graphical interface so let's go ahead and have a look okay so i will open our sqlite3 weaver and in here what i have to do is only browsing the file of our database files so once i click on file and choose the open database option then i should point it to the file that we have just created and as you can see i'm inside the directory of our project and what i have to do is just selecting this and click on open now once i do that then you can see that we have in here our tables and we have only one table that its name is item now if we want to see its columns then we can basically click here on that arrow and this will display you the columns that we have created to create this table so you can see that we see all the columns in here and if you want to see the actual information inside that table then you can go easily by right clicking and click on browse table and you can see here that we have actually stored information and you can see the exact information that i showed you from the python shell so this is something that is optional for me this tool was very comfortable when i developed some flask projects and i really recommended to look up for such a tool that will display the information for you visually so it will make your lives easier in certain cases all right so now if we take a look to what is inside the market.py file currently we have a model here and down below we have several routes that we have created now we are going to create more models and more routes in the future and so it might be a great idea to have a python file that its name is going to be models.py and also routes.py where we will store all the routes now we are going to spend a few minutes on how to reorganize our project because it is not going to be as easy as grabbing the models to a models dot py file and import stuff because we are going to end up with a forbidden import and we are going to explain that in a few minutes so let's actually try to split our different flask elements to different python files so i will start with creating a new python file and for sure i will name it modules dot py and in here i will grab our single item module and i will try to paste it in inside our modules and currently i will allow myself to ignore that db variable that is not existing here and i will go back to the market dot py and i will do the same process by creating routes.py and then i will go back to our market.py and i will grab in everything from here and paste this in over here so we could pay attention that we have several arrows because several functions are not loaded inside that particular file so how we are going to get out of this so let's first go back to our market dot py now as you know in python when you use the import keyword to import some file then what python does it executes the entire file line by line so if you remember before we actually moved the routes and the models we used to have a market.py file with modules over here and with routes down below now we could basically go ahead and use here import modules and import routes but we still have to figure out how we are going to give these models.py the db variable that it's missing so again we could try to solve that by moving that line to modules dot py so i will paste this in inside here now we also end up with missing the sql alchemy instance so again we could grab this in from here and paste this in above here but we are never going to get out of this because there is always going to be something missing in each file and then we will end up with something that is called circular imports now what secular imports are it is basically two files are trying to import from each other and it is something that is forbidden in python because each file will end up with some missing variables when it tries to load some variable from python memory so in order to avoid this python comes up with something that is named packages now we can basically package our entire application inside a new directory let's call it something like market and then we can create one more python file for example we can name it run execute start something like that and then that python file will know how to import everything step by step and the only thing that we will have to do is calling that specific file and then that python file will take care of the rest so this is the design that we are going to implement in that video and so by the end of this video every file will be at its own place and everything will totally make sense for you so let's actually get rid of those lines that i just pasted in over here and revert them back inside our market dot py and then we will remove those again and then now we will basically go ahead and create a package and then we will name it market so let's see how we can do that great so first of all we will go ahead inside our flask market directory and we will create that single file that is going to take care of everything that i just discussed about and i will name it something like run okay so it is going to be responsible to execute our application and what i will do now is grab everything from our market dot py and i will cut everything from here and i will basically paste this in over here now as i have completed this basically i can allow myself to delete the market.py file because the routes are here and then the models are here so the market.py is quite empty and i can allow myself to delete that so let's go ahead and delete that i will use the safe delete option all right and our next step here will be to create new directory and move our templates modules and routes dot py into that directory so we are packaging every flask element into a new directory that is named market so let's go ahead and create a new directory here and i will name it market and then we will basically move everything from here to that market directory so in python that will be as easy as grabbing it and just hovering it inside the market here then you can see that pycharm auto completes me by asking if i want to move some files into that directory so i will basically use the refactor option here and then you can see that our modules for example is located inside the new directory now i will do the same with routes and also with our templates great and last we will also move in our market.db okay so let's close each file over here so our structure right now is that we have our market directory and we have our run.py python file which is outside of that market directory so let's see how we continue from here okay so if we actually take a look to the lines that are left inside our run.py file they are basically some initialization lines that contains very important information about our web application now what we must do with those lines of code that are left over here is to move them to a special python file that is called double underscore init now when you work with python packages every python package that is considered as a regular package is going to include one special python file that its name is always going to be double underscore init double underscore and what is so special with that file is that when you import it then before it loads what you want to import to your file it is basically going to execute that particular file that is named double underscore init double underscore so it totally makes sense because whenever we want to import some objects or variables from our application then we probably want to execute those lines of code because those lines of code are what responsible to start our flask application so we will go ahead and do that so i will basically go inside our market directory and i will create an initialization file that will be responsible to define this directory as a package so i will name it double underscore init double unscore as i said and i will move in whatever is inside that run that py to that double underscore init double underscore file now what is so special with the process that we have done until now is that if we are going ahead from our run dot py file and we try to import market then it is going to recognize it as a package because we have included that double underscore init file so if we were to try to import that app variable that we have created then it is going to be perfectly fine because it recognizes that variable from our double underscore init file and anyway it is going to execute it as a first step because this is why we have that double underscore indeed file and actually the next line that i can allow myself to do here is using app.run and this file is going to be that pointer file that is going to do the rest of the job of importing everything so this is how it is going to work right we are basically going to import our application from market package and then we are going to run it but before we actually try this out let's add here one more argument and it is going to accept some arguments that we already familiar with and it is going to accept here debug equals true so we don't have to set up those environment variables anymore and one more thing that i'd like to add here as a convention in python is to test out if this run.py file has executed directly now the way that we can check that is by writing the conditional of if double underscore name is equal to double underscore main and again if you don't know what this conditional is about i have a video on my channel that you can definitely check out what this special if name equals main does but basically it checks if our run.py file has executed directly okay so now let's go ahead to our terminal and try to see what will happen if we execute that run.py file now i know that there is a great chance that we are going to fail and receive some errors but i want to show you step by step how we are going to overcome those errors now that we have our package set up so i will open my terminal and basically the only thing that i have to do now is going ahead and execute that run.py file now our web application will start and if we actually try to access it then you can see that we receive errors that the root url is not found now that doesn't make sense because if we take a look to our python then we can see inside our routes dot py that that we have the route for our root url but the reason this fails it is because the double underscore init file does not recognize the routes that we have created inside that route dot py file so our first step here is going to be to complete this dunder emit file by saying from market import routes and as you remember if we import certain file then python is going to try to execute what is inside that file so now we can go back to our web browser and the test results out now you can see that our web application is probably down right now because we see that this site can't be reached and as you can see we started to receive certain errors about the import so in that route.py file we don't have the application defined so let's go ahead and fix that so i will go to our python and i will basically type in from market import app and as you can see that app errors are started to disappear but we still have left with the render template error so we can also go ahead and fix it by saying from flask import vendor template and then we also have one more error that we must fix in here and that will be the import of our models dot py because as you can see we have a line here that says item.query.org and it doesn't know anything about it because it is not a recognized model and i can basically import it like we can import from a regular package in python and that will be by saying from market dot models import item so now we have pretty much everything set up in our routes dot py and if we have a look inside our models dot py then we still have some errors over here left over so i can basically fix it by saying from market import db because we can import it from our dander init file and now everything should work so we can basically test this up by going to our terminal and re-run our application and i will clean my screen again and i will try to run that py file again and now our website is up and running and i can basically test if everything works properly and if i refresh it then you can see that we receive our web application as it's supposed to now if i navigate to that market page then you can also see that everything is quite great so this means that everything works great and we have completed our packaging successfully now i know that there was a lot of information that will probably have to sink in but i hope that the packaging process was clear and you pretty much understood everything about what i have done here so again the main idea was to package everything that is related to market and then having one single file that we basically can execute it and then this file will be responsible to do everything for us now i just realized that i did not specify a lot of times throughout this tutorial that our code is available from the github and you can definitely go down below to the description and bring the link for the repository that includes the code of that tutorial and you can download it in the way that you like them so you can also use the command of git clone or you can download it as a zip file up to you but basically it is a great idea to go to that link and follow the code that i'm writing throughout this tutorial okay so let's go ahead and continue so i will basically have to deal with a way how i can accept users to our website and the way that we are going to do that is obviously by storing some information regarding our users in a database so it totally makes sense to go ahead and create a new module and then we will store some special fields like username password and stuff like that that is going to be our columns within that model so let's go ahead and do that so i will go up top here basically i'd like to remain the item as our second module and i will write in top here class user and it will inherit from db.module like we did in our previous modules and our first column would be the id again so as you remember i said previously that it is a convention and it is a must thing to have that id field because this is how the flask wants to identify each of your objects by their id numbers so i will allow myself to copy this line from here and paste this in as a first line over there and now i can allow myself to continue and creating some new fields so i will go ahead and create username equals to db dot column and i will make that to be equal to db dot string and i will close this out and it is a great idea to limit our users by saying length equals to 30 so it will be maximum 30 characters per each username and this is something that we want to keep unique because we probably don't want to let our website users to have multiple usernames that they are the same so unique could be true and we will also specify nullable equals false and just to follow this exact same order like we did previously i will go here and type in nullable equals false and i realize that i missed the comma here so let's complete that out okay so this is our username field and as you know in most of the websites we also have to provide our email address when we register to a different site so it is also a great idea to have an email field so it will be email address equals to db.column and this time i want to limit this email address as well but i have to raise our limit a bit so if there is a username with a length of 30 characters then it might be a greater idea to give our email address a limit of 50 characters so there is a lot of space for at email.com something like that so i will also make that nullable equals to false and also unique equals true that is quite making sense and our next field here would be our password now i'm going to name this field a little bit different because we are not going to store passwords as plain text inside our database now doing something like this could lead to a lot of security risks and that is something that is basically called make hackers life easier to pull some information from your website's database so you'll probably want to avoid this by storing the password not as plain text but besides you'll want to apply some hashing algorithm or some another way that will encrypt that password so even if there is a hacker that is going to steal some password information from your website he doesn't have a lot of things to do with that because it is encrypted so i will name this field by saying password underscore hash and that will be equal to db dot column and we are going to receive here string again now i'm going to give this length 60 because the mostly used hashing algorithm that flask allows us to use will always convert the passwords to being 60 characters so this is why i'm going to specify here length equals to 60 and i will continue on by saying nullable equals to false and i actually don't have to write here unique equals true because it is totally fine if two people have the exact same password in our website now this is the password field we still have some more fields to set up for our users and the next one will be the budget now if you remember from the very beginning of this tutorial i said that we are going to apply a budget system for our users so it totally makes sense to describe our user's attributes by one more attribute that its name would be budget so i will go ahead and say budget equals to db dot column and that time this will be equal to db dot integer and we will go here and continue by saying nullable equals false and we are also going to set a default value when this user object is created now you'll probably want to give some amount of money for your new users to start buying and selling stuff from the market so we will set the default value for that for example to 1000 so the users can at least have 1000 coins at the very first registration attempt okay so it totally makes sense to set up a value like that and one final field that i like to add here before we close up this module will be a field that is going to be related to our items module now what that means it means that we want to allow our users to own several items because this is what this website is going to be about so in database definitions this is something that is called relationship between a two tables now in our case we use modules because we work with python but we have to use some special field that is called relationship and inside that relationship field we are going to describe several arguments to make the model to understand that the user can own some items okay so let's go to here and write in items equals to so we will type in db dot relationship like that and we will close our parentheses and the relationship is going to be with our item model so we will say that by writing the model name inside a string like this now continuing from here i am also going to type in back riff equals to and we will open a single code and inside here we will say owned user and what backref does it is basically a back reference to that user model so for example if we have one user and then we want to know the items that this user owns we are basically going to grab the object of the user and we will access the attribute of items but let's consider a situation that you have an iphone item inside your database and you want to know its owner now you are going to grab the item object and then you will access it by the attribute of owned user and that is because you specify the back reference of that item so it is quite important to provide this back reference because it will allow us to see the owner of specific items so the last argument that i will say here will be lazy equals true and that is something that we also have to set up here because if you don't set up the lazy equals true then the sql alchemy will not grab all the objects of items in one shot so it is quite important to specify the lazy equals true in that case now i want you to take a look how this db is not actually a column besides it is a relationship so what that means it means that this is not actually going to be stored as a column when we try to inspect inside our database so it is quite wrong because we also want to store information about certain users that are owning some items now the way that we are going to do that is by saying to our items module which user is owning it so we will go back to our items module and specify one more column that we must create in order to make this relationship to work successfully so we will go here and we will type in owner equals to db dot column and this will be an integer and the next thing that we want to write here is the relationship to the user model so i will say db dot foreign key like this now what foreign key does it search for the primary key of your model from the module that is related to now if you remember i said previously that there is a great reason that we have to create this id in here in order to the sql alchemy to understand each row that is going to be stored inside our databases so now if we go ahead and create foreign key we can basically say that this foreign key is going to be related to the other modules primary key so we will say in here user dot id and this is related to the each unique row that is going to be stored in that id so it is quite important to write here user dot id in lowercase okay so now i'm back at my terminal and i like to create all the tables from scratch inside our database so we will go with python and we will use here from market.modules import db and then we can basically say db.drop all now this will delete entire information from your database including all the tables so we will say that and then we will recreate everything now i'm doing this just because we want to clean our information before we test new things out but in production when you add a new table you don't always have to delete the entire information basically you could also execute create underscore all but i just wanted to show you that there is the option of drop underscore all as well so now if i go ahead and create everything then if i don't receive arrows then it means that everything looks great now we can continue by importing the modules so we will say import user and item again from our market dot modules now we can basically try to create a new user to see if everything has worked properly so we will say u1 equals to user and we will specify the username this will be equal to jsc for example and we will write in password underscore hash this will be equal to just random string of numbers and we will also say email equals to something like the following now if you remember we also have the fields of budget and the owner now i did not specify nullable equals to false on both of those so that means that it should be enough now i guess i missed the email here so we should fix that to underscore address and now we are fine now let's clean the screen a bit we will say os dot system and we will execute this cls inside here and now i can basically go with db.session.ad and we will add the u1 in here and we can commit our changes by saying dot db.session.com okay so now this should be enough for our user to be stored inside our database now to see this we can basically execute user.query.all and then you can see that we have one user with the user one statement right here so it means that everything worked great okay so i cleaned the screen a little bit here so i also want to test up the relationship if it works great so we can basically create several items quickly and set their owners to the user that we have just created and see if everything works well so i will go ahead and say i1 equals to an item and i will go by saying the name equals to iphone 10 for example and we will type in description and we will just write in a short description here and we will say barcode equals to a string like that and we will type in price equals to 800 for example so i just missed up the desk we should create the description like that okay so everything works great and i will go by saying db.session.ad and i will add i1 and i will now use commit so we will commit our changes now let's repeat ourselves with another item so i will clean the screen here quickly and i can load the previous commands by using the arrow signs so i can basically change this to i2 and this to laptop and i will change the description to description too and the barcode here will be a little bit different and the price will be 1000 that time and we can repeat ourselves again by saying [Music] like that okay so now we have two items stored inside our database so we can verify this by saying query dot all and now let's try to assign an ownership to the iphone 10 item so we have to go and filter this specific iphone 10 object and we can do that by saying item.query that filter underscore by and i can filter by name equals to iphone 10 like that okay so it also makes sense to assign this into a new variable so i will go ahead and with item one i will assign it and now if i access item one then you can see that it returns us a base query and now we can basically use this first method to grab the specific object itself so now i have the item1 object in here and now i want to test up the results if i try to access the attribute of owner and now you can see that it returns us nothing because it doesn't have a owner now to continue from here i can basically say that i want to assign the owner of item 1 to the specific object of the user that we have just created previously with the username of jsc so it will look like something like the following so it will be item1.owner and this will be equal to user.query.filter underscoreby and i want to filter by the username equals to jsc and if you remember this entire statement here returns us a base object and we have to access the actual object by saying that first and as i have done that then i can continue on to db.session.com and i can assign the item one and now sorry i should have type in here add great and then i should have continue to commit now as i have done that then we can see a several errors over here now i can see that we have this update item set owner where item.id equals to a question mark now i have a feeling that i know why this happened and it sometimes that always may confuse every one of us and the point is we have to understand that the only way that we can assign the attribute of owner is by specifying the id of the user so if you remember our foreign key is only going to accept the attribute of id so this is why we have done a great job by filtering the specific user but only we had to give it the attribute of id so let's go ahead and fix that so before everything let's clean the screen for a minute so it will be cls inside os dot system and before i actually take different changes inside our item one we have to execute this command which is going to look like db.session.rollback so we can roll back our previous changes and commits and once i execute that if i did not receive any errors then it should be fine and now i will just type in the exact same command that we wrote previously so it will be item1.owner and it will be query dot filter underscore by and we will filter by jsc and after the dot first in here we have to give it the attribute of id and once i have done that then i can basically add it to our session which is clean because we have rolled back the previous commits and now we can try to execute the commit and this should work so if i was to go ahead and see the owner then you can see that it returns us one and the reason it returns as one it is basically because this is the foreign key of the owned user now we can also test this by filtering the item specifically so we can go with i equals to item dot query dot filter underscore by and we want to filter by name equals to iphone 10 like that and now we can basically try to see the back reference of the item that i talked about so if you remember we had that backref attribute set up so if i was to go ahead and execute i dot owned user then we would receive some errors because again i missed the dot first in here and now i can run in on user then you can see that it returns us the actual user that owns this item so this is quite great and this is a great achievement that we have done until now so so i hope you understood everything about how relationships of databases working because it is quite important to be aware of that situation so this is the actual idea of our website right we want to own items as users inside our web application okay so previously we have created our user module but we currently don't have any special way to create users to our website besides the only way to do that will be by our terminal and we are probably looking for a way to customize a nice looking html page for our customers so they will have the ability to register to our website so the way we can do that is by customizing an html form now we probably want to make this form smart enough to check certain things to see if this information is valid so for example you can't create a user if there is already a user with the same name or if your password linked does not meet the requirements of your website or anything else that is quite dealing with validating stuff when it comes to register to a website so in order to create our forms to register smart enough flask delivers already a built-in package to create phones and this also allow us to display it nicer on our html templates so in order to start working with this we need to go ahead to our terminal and install some packages so this is why i will open my terminal here and i will basically type in some pip install commands so the first one will be pip install flask dash and this is the first package that will allow us to create nice looking forms and then later on to display them on our html templates so i will clean the screen here and our second package will be pip install wt forms so you can see that it is already installed probably this was a secondary package under the flask wtf so anyway just write this command as well for safety and let's continue from here okay so as i said previously the forms are going to be a quite different element in our flask application so this is why it totally makes sense to create a python file that we will name it phones.py and then each form that we are going to create for some situation will be stored there so let's go ahead and do that so i will go under my market directory and i will create a new python file we will name it forms and here we will write our forms that we want to display them on our html templates now the way that this is going to behave is quite similar to models because we are going to create classes and then we are going to create some fields inside our classes and then that way those fields are going to be the required fields for our customers that they have to fill in in order to register to our website so let's go ahead and do that but the first step is to actually import those libraries that we have just installed in order to create those forms so i will basically go with form flask underscore wtf import flask form and then we also want to import some special fields that are going to be recognized by a special type of field so for example we might have an integer field for our users if we want to ask them about the year of birth or we might have a string field if we want to ask them about their name so this is why we should go ahead and also import the special fields by saying from wt form import string field now we can also go ahead and import more types of fields but currently we will only start with the string field okay so we will start by creating our register form so it is going to be by saying class register form and this will inherit from the flask form class that we have imported over here so this is why i will type in here flask form so the next thing that i will do here is creating some fields that they are going to be recognized as our form fields so i will start by creating a username field because it totally makes sense to register our users to ask for a username so it will be equal to string field because this is a string and then there is a convention to give a label for each of our fields so i will provide in here label equals to username and i think that will be it for the username field now we are also going to ask the email address from our user so i will go ahead by saying email underscore address equals to the string field again and that time i will label it by email only so this should be enough now i am also going to create two different fields for our passwords so it will be password one and also password two now the reason you want to do this because mostly in each website you see a field about the password and also about the confirmation of that password so this is why it makes sense to create two separated fields and then later on we are going to write a validation that is going to check if password one is equal to password two so we can submit the register form successfully so to create this a string field is not considered as a best practice because the wt forms has a dedicated field for password fields so i will go here and i will import it by saying password field and then i will create it as a password field over here like that and i will close the parentheses and the same will be for the password tool as well so i will create it as a password field now let's give it their labels as well so it will be password1 for the label of that and for the label of password2 it will be password2 alright so now that we have created those fields we also have to create the field that will allow the users to submit their actual information now when you see some forms not only you'll see areas where you have to fill in some information but you also see a button that you have to submit your final information so this is why i will create a field that is going to be by the type of submit so i will go to our second line here and i will import that submit field and then i will create one submit field so it will be submit equals to submit field and again its label is going to be submit so i think this should be enough for now for our registered form later on we are going to go back to that register form to write some validations in order to make our form more secure okay so now it is a great idea to import this registered form class from our routes now we currently don't have any route for our registration page so let's go ahead and create one so i will go to my routes dot py and i will zoom in the phone here and i will start creating a new route for our register page so it will be at act dot route and i will navigate our users to forward slash register and then we will create this register page route by calling this function register page now the first step here would be to import that form from the forms dot py so i will go up top here and i will import it by saying from market dot forms import register form and inside that function i will basically use the register form class to create one instance of it so it will be form equals to register form and i will close this up like this now as we have completed that we have to look up for a way to display the fields of that phone inside an html page now the way that we can do that is for sure by rendering a template with the name of register for example and then we can pass as information our form instance so we will say here return render underscore template and then we will send our users to a template named register.html and i know that we did not create it yet but we will do it very shortly and the information that we want to send to that template will be that form instance that we have created here so it will be form equals to form and i think that will be enough for this stage and now let's go ahead and create this register.html template so it will be here and i will basically create a new html file we will name it register and then we will replace it with some html code that is going to be responsible to display that form in a very nice way now i will delete the auto generated html and i will start by for sure extending our base template so if you remember we have our base template that we have to inherit when we create a new template so it will be curly brackets and then the percentage signs and then the closure for our curly brackets and between those we will type in extends and then we will extend our base.html now as i have completed that we have two blocks that we should use and then contain some information inside there so if you remember we had inside our base dot html a blog title and also a blog content so i will copy the blog title and i will paste this in and i will also copy the blog content and i will paste this in as well now let's fix the indentation here a little bit and we will continue from here now if you remember in the blog title we are allowed to provide information that is going to be displayed as our tab names so it makes sense to type in something like register page and in here let's actually give a random information currently to test if everything works properly so i can validate myself by only writing some basic html code so let's write in here register form inside the h1 tag all right so we have one more step to complete before we can go ahead and actually test this out and that will be to create a special secret key that is going to be identified as the secret key of our flask application now the main reason that you want to do that in this stage it is because if you go ahead and test the form out right now nothing is going to show up because when you create forms in html you actually have to provide one more security layer in order to show this form up and that is simply because we change our request type to our clients so until now we were able to display html pages for our clients but when it comes to forms now our clients are going to be able to submit actual information towards our database so this is a quite different action that must be secure enough so this is why we have to create a secret key for our flask application so the way that we can do that is by generating some series of characters that is going to be used as our secret key so i will open our terminal and i will go inside python and i will import the os library because simply we can generate there a hexadecimal random characters so it will be by import os and then we can basically go ahead and say os dot u random and then we can provide here the value of 12 so it will be by the value of 12 bytes and then we can basically go ahead and convert this to hexadecimal values and then the value that we'll be receiving back would be the secret key that we auto generated for our application now there is nothing wrong with going ahead and generate more secret keys but just make sure that if you use one then stick to it throughout the development of that application so let's grab this secret key and go back to our python and navigate inside our init.pi and then here we have to write in some new configuration so it will be app.config and then our key here will be secret underscore key and if we paste this in right there and this should be inside single quotes as well then this should be enough to display the form that we just created so i will go back to my terminal and we can exit the python shell now and we can basically execute our application with python run.py and then we can navigate back to our website and try to see what will happen if i go to fort slash register and then you can see that we have our page up and running so this is quite great now one more thing that i like to do before we continue is to actually configure that navbar button where we can click on it and then this will lead us to the route of the register page so if you remember previously we learned about the url underscore 4 built in so let's go ahead and configure that so it will be as easy as going to our base dot html and identify that register page which is right there so this is the anchor tag for our register page and if you remember from previous examples for example for the home page we use this built-in url for function so i will allow myself to copy the exact statement and paste this in inside our href attribute and then this could be changed to register underscore page and now we can test this out by refreshing our page and for example navigate to our four slash home and we can click on slash register then you can see that it works great so now we can continue on customizing that form okay so i'm back in my register.html and in here you could notice how i deleted the code inside our blog content now inside the content we are going to put the form itself and the way that we can access the form instance is referring to the variable that is passed from our route with jinja syntax so it will be by saying form within double curly brackets so just to check if this works properly we can basically navigate back to our website and see what happens if we go with fold slash register then you can see that we see the object itself of the form so this means that we can access the form itself now to access the actual fields and to visualize them better we are going to take some different actions in here so we have to create the form tag which is a built-in tag in html syntax and we also have to specify some more attributes in order to the form to work successfully so one of them will be the meta type now i did not talk about request methods before but basically when it comes to websites you have a lot of request methods that the clients can provide and the most known request method will be the get method where clients are requesting to display some information on different web pages but there is also one more different request method that is called post and the post request is a kind of request that is going to affect the database of your website so since this is a critical action to take as a website client then you have to specify that the method is going to be post so it is important to provide this kind of information in here and i will continue on by saying class equals to form dash register and the last attribute in here will be the styling so we want to style our foreground color to white so it will be color column white so i'm doing this because we are working on dark mode and it is quite important to have the foreground color set as white okay so inside our form tag we can basically refer to our form fields by saying so i will open the curly brackets one more time in here and i will first call the label of our form fields and then i will call the field itself so you will see the effect of that just in a second so i will say form.username dot label and i will open and close the parenthesis here and below that we can say form dot username and i can open the parentheses and close them up here again now what is so special with that flask forums is that this statement is going to accept attributes like in real html code so we could say here class and then we could basically give it a bootstrap class so i will say form dash control so it will be responsible to display that field a little bit nicer and we can also give it a placeholder so our clients can understand that this field is designed for providing the username so we can say first of all let's add a comma here and we can say placeholder equals to user name like that and let's see the actual results of a code like this so if i'm going to our web browser and refreshing that out then you can see that we see an empty field where we can provide some information now i know that this looks quite ugly and in most of the websites the information of filling a form is starting not from the left position so we can fix that by containerizing those fields inside one more special html field so let's go ahead and do that so i will open our pycharm and in here we can containerize our form inside div tag so i will allow myself to type in here the class container so i will allow myself to paste this form inside those div tags and let's fix the indentation here a little bit and then let's test out the differences so i will refresh this out now you might be bothered by the results from that username in here but this is something that we can change in our forms dot py so this is the label of our username field so we called basically open our forms dot py and we could change the label so now you can understand what the label does it basically gives a kind of secondary title for our fields so we called say here user name like that and we could also change that to email address like this and we could also add here password like the following and we could also change this to confirm password like that so it makes a lot of sense to display the label of our password tool as confirmed password because it probably looks nicer to our clients so let's see the results of that so if i refresh it then you can see that we have a nice secondary title for that field now the way that we are going to continue is going to be by copying and pasting those form labels and the form fields itself so we can basically copy and paste ourselves four times and we can change this to email we can also change that to email as well and we can change the placeholder to email address like that and we can do this for our passwords as well so i will paste this in over here and this will change to password one and this is going to be changed to let's scroll down password in here and this is going to be password one as well great so now i can duplicate this one more time and we can change this to password tool we can change this to password two and this will be confirm password now to test the results of that we can refresh it you can see that we receive an error and that is fine because we defined the email field as email underscore address so let's fix that quickly so it will be underscore address and underscore address as well now you can see that i trained to not cut the arrows that i received throughout this video sometimes because i really want you to be aware of the possible arrows that you can meet throughout the process of writing any html code or any python related code so this is the reason that i'm okay with the arrows and handling them on the fly okay so i will refresh that out then you can see that we receive a lot of nicer form in here now i want to give a nice image for this form and i also want to give a h1 tag so the users can see a nice big title now the code that i'm going to paste in here you can find it from my website because i put all the code snippets in the flask tutorial section which you can find in my courses so i will paste it in over here and you can see in the first tag here that i have an image tag which is going to be responsible simply displaying the logo of my website and the h1 tag in here that is going to say to our users please create your account so let's just fix the indentation in here and i think this should be it and i also want to add here a break line tag so we can have a separation between our header to our fields okay so if we test the results then you can see that we have a great result where we see the logo of my website and we also have a nice title now it could be a lot better if we could centralize these objects so this is something that we also can apply and the way we can do that is by going in here and overriding the body tag of our html file so i will allow myself to make the font a little bit smaller here and what we can do here is basically wrapping the entire div with a body tag so we can say here body and then we can basically use the class of text dash sender and we can close this out and we can move the closure of our body to the very last line just above the end block and now if i refresh that out then you can see that we receive a nice looking form where everything looks pretty clean in my opinion now there is one more thing left that is remained to close out this form and this is the submit field that is missing in here so we can basically go back to our register.html and we can add it in here so i will call the ginger syntax in here by using the double curly bracket and i will call the submit field so it will be form dot submit and now in here we can provide some bootstrap classes as well so it will be class equals to and then we will type in the classes that we want to include to customize this submit button a little bit better so it will be btn and i will type in btn-lg which will responsible to display this button larger and i will also say btn-block and this will expand the button to the entire forum and i will also type in btn-primary so this should be responsible to display the button in a nice blue colored version so i will save this out and i will also add in here one more vr tag so we will have a nice separation between those and okay so now we can basically test the results by refreshing this page and now you can see that we got the submit button but we have the annoying submit text with all the lowercase now this happens because of the labels that we have created for each of our field again so we should change this to something like create account and once i have done that then i can verify myself by refreshing it now you can see that we receive a nice button for the create account now nothing is going to happen when i click on create account and when i fill in some information and actually this is something that we have to handle in a separated way inside our routes.py and we will do that very soon all right so until now we were not able to configure the behind the scenes actions of what happens when we create the create account button now to do this we have to go to our routes.py file and then we have to go for the route where the register form is located and then write some pure python code over there so to do this i will open my python and in here i can basically handle what happens when the user submits on the create account button so the best practice in that case will be to start by this conditional so it will be if form dot validate on submit now there are two main reasons that you want to execute this conditional before you actually go ahead and submit changes into your database okay so the first reason you want to execute that is you'll want to verify that those comments that i'm going to write in here are only going to be executed when the user is submitted on that button so this on submit part is actually checking if the user has clicked on the submit button of that form and the second reason you want to execute this it is mainly because we are going to write some validations that are going to check for certain requirements before this form becomes valid so i'm talking about conditions like you see in real register pages in real websites for example your password should be matched or your user name should not contain more than 20 characters and stuff like that so this is why it is very important to execute this conditional in here and once this returns true then i can basically go ahead with user to create like that and i will make that to be equal to an instance of user and it is a great idea to import it from the market.models in here so i will basically add a comma and i will import the user and once i have done that then i can basically give the arguments that are required to create a user so i will start by saying username equals to and in here i actually want to provide the value that is received from the username field within the form so i can do this by saying from dot username dot data so this is the way that we are going to pass our fields from the form and i will continue on doing this with the email address as well so i will say email underscore address equals to form dot email underscore address dot data and i will perform the exact same action with password so it will be password equals to form dot password one and in here i'm passing password one by purpose and you will see in a few minutes why i am doing this so i will say that data in here again okay so this should be enough to create the instance of our user and once i have done that then i can basically execute the same commands to submit the changes towards our database so it will be db session dot add and i will pass in the argument of user to create and i know that we did not import the db variable in here so it is a great idea to import it now i will go down here and i will say from market import db now the reason i can import it directly from the market package it is mainly because it is located in the under init file so i don't have to go inside dot something okay so it is quite great to import it that way and now i will go back to our route and i will say dot db.session.com and this will save our changes to the database and once we have done that then we probably want to redirect our users to a different page now it quite makes sense because now they are registered to the website and now we can show the user the items that are available on the market so i will use the built-in redirect function that the flask package offers us so i can go up here and i can go for that line and i can basically import the built-in function which is called redirect and i will also import the built-in url underscore four function that we used previously in our templates so we will go down here and we will see how we can redirect our users to a different page after the user is clicking on the create account button so i will go right after our commit command and i will say return redirect and in here the redirect function expects for an hard-coded url now if you remember previously in that tutorial we said that it is not a great idea to give arguments as a hard-coded urls so besides doing this i will say url underscore form and i will give the url underscore for the name of the route itself so it will be market underscore page and this should send our users right to here so it is quite great okay so we can just test this out by going back to our chrome browser and refresh that out and then now let's try to create a random account and see what happens okay so we will say here jsc 2 for example and we will fill in some dummy email and i will just type in very basic password and i will try to create account now you can see that we receive method not allowed and actually there's a reason that i wanted us to see this message because it is quite important to apply the step that i'm going to talk about now when it comes to web requests we said that we have several request methods and we should allow our routes to handle post requests and the way that we can do that is by customizing the decorator of our route function so i will go right here and i will say methods equals to and i will open here a list and i will insert two elements and i will give get and i will also give post okay so it is important to apply this step so our route could handle post requests and before we continue sorry about that but i think that we mismatched this line in here and this should be password underscore hash equals to form.password1.data so make sure to fix that before you continue alright so once we have enabled the post request in that route then there is one more important step that we have to configure before we test this out now when you send information from client to a server then it gives a huge opportunity to the hackers out there to steal that information and one of the known malicious attacks is called cross site request forgery and this attack is basically just a way to steal or perform actions against your database that are unwanted and to protect our website from such an attack flask delivers us a very easy future to apply a protection so the way that we are going to do that is as easy as going to our register.html and right under our form method post html tags we are basically going to say so we will open our curly brackets to refer to ginger syntax and we will easily say form dot hidden underscore tag and what this is going to do it is going to protect us from the attack that i was talking about by generating some token that is basically again just going to protect us from such an attack and okay now we can save that file and once we have completed this let's actually test if our website is up and running and we will now go to our website and we will navigate to our register page and we will try to create a new account so it will be jc2 for example and we will try to provide in some random email here and we will try to fill in some password and now if i'm going to press on create account and going to be redirected to the market page then it means that the user has been created and if i click on that then you can see that this is the exact result so that means that we have created this account and we can test this by easily going to python shell and type in user.query.org and this will be responsible to give all the users and we probably will see the jsc tool account that we have just created okay so although now we have the ability to register users we did not set up any special policy regarding to how we want to register our users and what i mean by that is you saw previously how i created a user with a password that only contains six characters and we did not even write a python code anywhere in our project that verifies that the password and the confirm password are match so this is very wrong when it comes to web applications and not secure and actually this is a huge bug now to solve this we can basically write in some validations to solve that problem and then those validations are going to be executed before the form is submitted and the way that we can do that is by the flask validations package that is offered by the flask itself so let's go ahead and try to apply some validations to see that the data that we are receiving is actually valid so i will make the font a little bit bigger here and i will say down here from wt forms dot validators and in here there are a lot of built-in classes that are going to check for certain validations so let's say that we want to validate that the username length is maximum 30 characters and minimum two characters so we can do that by importing a built-in class that is called linked and now once i have done that then we can go inside our username field and we can call the validators argument and basically we can say that we want to validate the length so it will be length and then i will open the parenthesis here and i will say minimum equals to 2 and i will also say max equals to 30. so what this line of code does it basically verifies before the submission that the username value includes between 2 to 30 characters and we can write more validations like that in each of the fields that we want so let's say that we want to apply the exact same step for our passwords so it will be as easy as going to our password one field and say valley datos again and this will be equal again to a class of length i mean an instance of the length class and we can now provide here minimum equals to six and i actually don't want to set a maximum value for our passwords because if our users want to have a huge password then it is quite okay now we could copy the exact validation to our password tool as well but we probably want to avoid that because if this validation is going to be executed on password one then we probably don't need to execute it again on our password too because we want those fields to be matched and as i said that how we are going to verify that password two matches password one well the way that we can do that is by importing one more class from the wtforms.validators and we can basically check if password2 is equal to password1 when the form is submitted so it will be as easy as importing the equal to class here and go to our password tool and say validators equals to equal to and then in here we will pass in as a string our field that we want to verify that it's equal to so it is password one and it is quite important to write this down because that is what is going to verify that the password and the confirm password are match now if you remember the password too is the confirm password and you can memorize this because we have this label in here so this is actually a very important validation okay so some more validations that we want to provide in here is probably to check if the ad sign is located in the email address and the way that we can do that is also as easy as importing the email class from the validators and we can just say validators equals to email and this is easily going to check if the given value in the email address is actually an email address and one more thing that we can do with the validators we can basically give one more validation to each field and it will be as easy as converting the validator's value to a list in each of our fields so let's go ahead and do that we will just add square brackets in the end and in the beginning of each our values so i will do that in here and i will also do that in here and i will do that in the password too as well now there is one more reason that i have done this because we also want to verify that each of our fields are filled in with some information so i can basically import the data required class here and i can add one more validation by going here and press comma and now we can type data required and close this up like this and we probably want to copy and paste the same validation for each of our fields because we want them to be filled up so i will copy this out and i will paste this in in here and as well as in here and also in here and i will just go back to here and i think we are pretty much done with all the validations that we want to apply okay so now that we have completed this let's see in our routes dot py how we are going to handle those validations so we will open our routes dot p y and we will zoom in here a little bit and down here we want to check if some of the validations are failing or not so for example let's say that we had a user that provided a username with only a one character well in that case it is quite obvious that our python conditional is not going to go inside our form dot validate on submit because one of the validations are not meeting our requirements to create a user successfully so to check for errors that are arriving from the validations it is as easy as checking the form dot errors so if one of our validations are going to fail then it is going to be stored inside this field and since it is a built-in dictionary field then we probably want to check if it is empty or not before we actually put in some more python code so i will say if form dot errors is not equal to empty dictionary and what i say by writing this conditional is just as easy as saying if there are no arrows that are arrived from the validations so i will comment this out if there are not arrows from the validations like that okay so it is quite important to write in this conditional and once i have done that then we can basically iterate over the arrows that are arriving from the validations so since there could be more than one validation error then we have to iterate over the form.arrow so it will be for err message so just a shortened way to say error message in form dot arrows and as i said that this is a dictionary then we can basically access the values of that so i will say dot values and i will close this up and we will enter this conditional and temporarily we will basically print the message in the server side so i will just print the message and then we should see the error message in the python shell where we see certain logs about our web server that is running so i will basically print the error msg up and it is a better idea to actually write a formatted message so it will be something like there was an error with creating a user and then we will call the variable that we are iterating on okay so i think that we are all set up to test if that works properly so now i will open our website on the left pane and i will locate our terminal in the right pane okay so we can be aware if there are going to be any arrows when we create a user so now i will try to register and i will verify that our website is running so i will execute python run dot py and now we can see that we receive an unexpected exception here so it says that let's actually see it like that it says that we must install the email underscore validator for email validation support so i will say down here pip install email underscore validator so just make sure to run that and i believe this should solve the problem so once we go ahead and install this up and now we can run our web server again and now i see that everything works properly now we can refresh this and we are right in the register page so now i want to create a user with only a one character so it will be just j and i will put a valid email address so just something like that and i will not mismatch the password by purpose so i will create an account and then you can see that it did not redirect us to the items page unlike the previous result and in our web browser we can see that we received there was an error creating a user and we can also see that we have here field must be between 2 and 30 characters along so what that means it means that our validations are working properly now if we want to test multiple validations that are going to fail then we can basically try to mismatch the email in here by writing some numbers and we can unmatch the password and confirm password and we can try to click on create account and now we can see multiple arrows so we have the there was another creating a user with this message and we also have it for the message here as well and i think we saw this twice because i was looking up here so sorry and there should be three arrows so the third is that field must be equal to password one and we also see that invalid email address and i think that this explains that our validations are working perfect because we saw the results as expected now i know that this is not a great idea to display those kind of messages on the server side and in the near future we are going to turn those messages and we are going to flash them up right in our website so it is going to be very cool to do that because this way our users could also be aware of the different arrows that are arriving from the validations all right so if you remember this was the line that was responsible to display some errors within the terminal of our web server now to change this to being displayed on our html templates flask gives us a built-in function that is called flash and this is basically a function that will allow us to display all the given information inside our html templates so it will be as easy as changing this print to flash and for sure this is a built-in function that we should import in our first lines over here so we should type in here flash so we are importing that built-in function and the way that we are going to do that is by first flashing some messages and then we are going to go inside our html templates and we are going to use a built-in function that is called get flashed messages and what is so beautiful with the get flashed messages it will allow us to gather all the flashed messages as the function says okay but we are going to do that on our template with ginger syntax so it is not quite necessary to import it over here i just wanted to show you the function that we will be using so once i have done that then i can basically go to our template and use that built-in get flashed messages so it will be as easy as going to our templates and going inside our base dot html and we actually want to think of an area where it could be nice to display those kind of flashed messages now the reason we don't do this in our register.html it is because we want to gain the ability to display flashed messages for all of our templates so it doesn't make sense to call the get flashed messages in a specific template besides it totally makes sense to call it from our base.html so we will go right under our navigation bar and we will display the flashed messages right before our block content so i will just go here and i will use the jinja syntax to grab the flashed messages now the way that we are going to do that is by context manager so it will be with messages equals to get flashed excuse me like that messages and then we will close this function and we will pass in an argument that is going to look quite weird for you in the first look but we will explain in a second and i'm going to pass in here with categories equals to true now the reason that we are going to do this it is because in the future we are going to add certain categories for the different messages that we want to display so the important point here is to understand that not only we can display some arrows but we can also display regular information or success messages and we are going to see how we are going to do that in a few minutes now i just realized that i implemented the variable block and with the get flashed messages it expects for the block code so i will change the inner curly brackets to parentheses and i mean percentage signs and this should be great now we should close this with and wait like that now inside this block of code we also want to check if there are going to be any messages when each page loads so we can do that by easily saying so i will call the block code again and i will say if messages and i will close this up by saying end if and i will fix the indentation in here so what we got until now is a messages variable that is trying to grab all the flashed messages and then later on we are also verifying that the messages is not known so it is quite important to do that because we probably want to check if our messages are filled with some flashed message from our route now when we reach this situation it quite makes sense to iterate over the messages if it is not none because if you remember in some cases we could have more than one messages that we want to display to our users so this is why right inside our if statement in here we are going to say and we will call the block code again and we will type in for message in messages and then we will close this up by saying and for and now this is the actual area where we want to display some nice html output to display the different messages to our users so i will start by displaying this message in a very simple p tag so it will be just easily p and then we will say message inside a variable block so it will be message in here and then later on we are going to give this a little bit nicer customization but we will do that in a few minutes now we can go to our website and check if this works properly so if you remember in our route.py we actually flashing a message to our clients so this should be fine by only verifying that our website is up and running and actually try to go back to home and try to register again to our website so i will type in some wrong information in here and let's see if everything works properly so we will try to create account and then you can see that we receive those arrows with the actual errors that we had when we try to create account now if we zoom in here a little bit we could see that we received the output as python tuples so what that means it means that our get flashed messages divides in the output into two important things and the first one is the category and the second one is the actual message so what that means it means that we can change our iteration a little bit to make it look even nicer so we could go back to our pycharm and actually let's go to our base.html again and we could add in here one more variable so we could unpack the results of what is inside the messages so i will say category and then we will add a comma and then we will only display the message itself and once i do this then we can basically try to refresh it and click actually continue and then we can see that the result is quite different okay so this could be one way that you could display different messages to your users but we probably want to give the user a little bit nice display to those kind of messages so the user could be aware if this is an error message or just an information message or a success message or something like that and we probably want to design it a little bit more colored rather than just displaying a blank white text so the way that we are going to do that is by going back to our pycharm and adding in here some categories to our flash message so if you remember the get flashed messages from the base.html are also responsible to grab the categories because we passed in this statement with categories equals to true so what that means it means that this grabs the categories as well so let's give our messages a category okay so we could go back here and we could say category equals to danger and there's actually a great reason why i typed in here danger and you will see that just in a second okay so once i have done that then i should re-customize this line in here to display a nicer message so the way that we are going to do that is by writing in some pure html code to display a nice message and also doing that with pulling some classes from the bootstrap framework that we have imported in the very beginning of this tutorial so i will start by saying div and i will continue by typing the class and i will say alert and then i will also say alert dash and then here i will pass in the category that we send from our route now here is the reason why i wrote danger it is because alert dash danger is going to pull the bootstrap class that its name is alert dash danger and that is responsible to display a red looking message so our users could understand that this is basically an error and something went wrong and inside those div tags i'm going to continue on by typing here button so this is going to be like a wide paragraph where the users could have the option to close the different alerts so i will continue giving here some more html attributes very quick so i will say by type equals button and i will also say class equals to m1-2 and i will also say mb-1 and then i will type in here close so those are some bootstrap classes that i memorize that will be responsible to just display it nicer so i don't want to waste a lot of time explaining what each class does and i will also say here data dash dismiss equals to alert and then i will also say area label equals to close so i'm going to explain some of the attributes when we see the actual results and this will totally make sense for you so i will go back to here and i will continue typing inside sorry about that and i will continue typing inside our button the message that we want to display so i will call here the span tag and i will type in here area hidden equals to true and inside our span i am going to type in some convention characters that the html could understand that i'm referring to an x icon so i want to show like an x close button like we have here in our pycharm this is the exact symbol that i want to refer to so i can just say times and then colon semicolon like that so once i have done that let's see the results and let's see the logic behind this html code okay so let's go here and let's actually put the pycharm in the left pane and our website in here so it would totally make sense to see those together so i will make the phones a little bit smaller and i will continue on from here so now i can zoom out our website and i can go to our homepage and try to register back again and i will again dismiss some information by purpose so i will say jc4 and i will type in some passwords and once i click on create account then we don't see the message and that is because i did not insert the message itself anywhere but you can already see the x symbol that i was talking about and if i click on then on that then it closes so i will just go inside our button here and i will just call the message by only calling the variable block and pass in message and actually i think this should be out of our button here so i will move this right under the closure of the button tag okay so once i have done that let's test the results again so i will go and try to register and i will type in a valid email but only i will not create proper password so i will just type in here some random characters and click on create account and then you can see that we see a nice looking error and our clients could really understand that we have something wrong and we also have the option to close this button by clicking on the x right there now the attribute of data dismiss and area label and area hidden equals true are what responsible to configure what the x symbol should do when we click on it but i don't want to get into much complex detail about html and javascript and some more further information that is quite not relevant for now all right everyone so i hope you understood the entire topic of how we can display nicer flashed messages to our clients now there is going to be one more thing that we want to solve about this registration form now i will try to create a user with a username that is already existing on our database so if you remember in the previous actions that i have completed in this tutorial i created already a user with name of jsc now if we try to create a user with an existing username let's see the result okay so let's go ahead and try to pass in some valid email and actually a valid password as well and if i click here then you can see that it leads us to an error where it says that the unique constraint failed now i know it jumped down here and this is actually referring to actual error but this is the error that i want to talk about so unique constraint field means that we tried to insert a user row to that item table that we have and then it failed because we already have a username with the name of jsc so we probably want to avoid display such a message to our users one this doesn't look nice and two we probably don't want to show our bugs and our code problems to the users so the way that we can overcome this is by easily catching this error a lot earlier before it leads to that sq alchemy integrity error so let's see how we can do that in python okay so i will basically open back our pycharm here and you can see that i'm already inside our forms dot py and there is a great reason for that now in here we want to write validation that is going to check if the attempted user from the registration form is existing or not and then we can catch up this unique error before it leads to the error from the sql alchemy itself so that way we will have a validation error and then we will be able to display to our users this nice red colored error message that we saw previously let's go ahead and do this and i will go inside the flask form class here i mean the register from glass and i will type in some function which i'm going to name validate username and i'm going to receive the cell for sure and i also want to receive one more parameter and we will name it username underscore tool underscore check okay so we are checking if the given username is already existing in our database and once we have done that then we want to query our user model to check if this username to check is already existing or not so i will go up top here and i will import our module and it will be from market dot modules import user and i will go down here with two lines so we will have a cleaner look and i will continue inside our validate username function and i will say user equals to user dot query dot filter underscore by and we want to filter the user object by username equals to username to check and what i'm doing by writing this line i'm basically asking our entire user object if there is a user with the username to check that is arriving from the registration form and once i do that then you can remember from the previous sessions of this tutorial that this entire expression returns us an object and in order to access the first object of it then we should go and type in first like that okay so if this user object is filled in with some information meaning that this entire statement returns an object then this means that there is already a user with that username existing in the database so we probably want to go ahead and type in a conditional like if user so i'm checking if the user is not none and in here i want to raise a validation arrow so it will be race validation error and i will just type in a message like username already exists please try a different username and you could pay attention that this gives us an error in here because we should import this built-in exception class from that line so i will say valley validation error right there okay so there is one more thing that i bet that confuses you in that case so we were able to write a nice block of code in here that is basically verifying that the user is not exist and then we raise an error if there is actually a user with the username that he tries to create now you're probably asking yourself how this validate underscore username is going to be executed in somewhere in our project now in that case what is so special with the validators library is that you are allowed to create certain functions in very specific usernames and then the flask form class is going to take care of the rest so by writing validate underscore username like that then what flask form is going to do it is going to search for all the functions that are starting with the prefix of validate underscore and then later on it is going to check for the next name after the underscore and then it is going to search if there is even a field with that given name and we happen to have this username field so this way our flask form class that we inherit from will know to validate underscore username because we have a field with the username right here so it is quite important to understand why i named this function that way okay so the flask form called understand that we are going to execute a validation for the username itself and we could also do that with our validate email address so we probably want to check if there is an email address that is already existing if our users are trying to create an account with an existing email address so we could do the exact same thing by going down here and typing in validate underscore and here we want to give the email address as our function name so i will go by again saying email address to check and then we will go inside our function and we will continue on by saying email address equals to user dot query dot filter underscore by and we will try to filter by email address equals to email address to check and we have to execute that dot first in here again and then we can say if email address then we can raise a validation error and then we could type in email address already exists please try a different email address okay so there's a great reason that i'm not copying and pasting because as long as i'm doing that then you are practicing how you can write such a complex code when it comes to sometimes rays arrows and conditionals and then functions with a very unique name so this is why i did not copy and paste um and i think this should be enough to see the actual results so i will basically go to our web you know what let's verify that our website is running and it is not so let's execute python1 dot py and then you can see that our website is up back again and now i can try to refresh our page and let's actually go to home and now we can try to go back to register and try to create some account and see the results of that and in here let's try to create again an account with an existing username but not with an existing email address so i will give here an email address like that and i will type in correct passwords and if we click on create account then we see an error again so probably something that we missed with writing the validations so i think we see this unsupported type when we creating the validation so and let's actually have a look if our validation is proper or not um so it is a great idea to go here and user equals to user query filter by and then we pass in this this username to check but i think that this should be a little bit different so i might see what is going on here now if you remember from our route dot py we used to access our actual fields with accessing the data attribute so i think this is what we have to pass in here to query our users so this is just the same approach so in here we create the users with grabbing the dot data and we should do that in our forms dot py as well so i will go here and i will say that data in here and i will do the same in our user query filter in the validate username so i will type in dot data and i think this should be enough to test it out back again because we probably don't want to refer to actual object of the username to check we want to refer to that dot data so let's go back to here and test the results of that so i will try to register back again and i will type in again a username that is already exist and we will change the email a little bit and the password like that and now if we click on create account then you can see that we receive an alert besides receiving a complex error so our users could be notified with that kind of unique arrow as well and you can see the message there was an error with creating a username username already exist please try a different username and that is happened to be the error that we have raised by ourselves now if we want to test this with the email address as well then we can go ahead and do that so if i remember correctly then we had an email with jsc at jsc.com so this should fail and if i click on the same password and try to create a new account then you can see that our validation error about email address is also very very fine and i think that this is beyond then enough to really have a very stable registration form for our clients okay so i'd like to start with changing the way that we maintain our passwords in the database now if you remember i said previously in that course that we are not going to store passwords as plain text now actually what happens now if we actually inspect to our database with the sqlite3 gui tool that i talked about previously in that course then we can see that we have two users but we see their passwords as plain text now this is something that is not considered as a secure thing to do so we are going to change this and we are going to store a hashed password and that is going to allow us to store crypted passwords so let's go ahead and do that and the first step for that will be to install a library with pip install command so i will pause our website for a minute and i will say pip install flask underscore be crypt okay so as i install that then i can clean my screen again and i can go to pycharm and import this library now again what this is going to do it is going to allow us to store the password as hashed password and not as plain text as we saw so i'm already located inside my thunder init file and in here we need to initialize this decrypt library i mean an instance of a bcrypt class inside that library so it will be from flask underscore be crypt import be crypt like that and i just realized that we forgot to delete this vendor template from here so let's go ahead and do that and down here i'm going to create an instance of that and we are going to rely on that to use it in our entire application so i will say be crypt equals to be crypt and i will pass our app as an argument inside the bcrypt class okay so once we have done that then we can basically rely on the bcrypt to start generating hash passwords rather than storing them as plain text so the way that we can do this is by going to our user model and start creating some additional properties now if what i say right now does not make sense to you then it is quite fine but in object oriented programming there are something that is called getters and setters so what this means it means that we can basically configure the way that we want to receive back in attribute and the way that we want to set the attribute so this is going to help us because we need to create one more property and we can name it password and then once we set that password then we can execute additional code to turn this password to enhash password so let's see that in action and i think when i write the code of that it will totally make sense for you so i will open my modules.py and in here we will start creating some additional properties now the properties are going to be set unique per instance so it is important to understand that and i'm going to go down here and i'm going to use the decorator of property so again this is just going to be like an additional attribute that is going to be accessible from each instance and once i have done that then i will basically name it password and not password hash like i did here and i will say return self.password so those lines of code are not doing anything special right now because what this says it says that okay i have a new property and i basically return it back when the user wants it or myself as a developer who wants to see some attributes and the tricky line is actually starting from here so i will now say password dot setter so basically we can allow ourselves to execute some lines of code before we actually set a password to an user instance so it will be dev password in here again and this time i will receive additional parameter and this parameter is going to be the password that is going to be filled in when we want to set that up so the parameter name is going to be plain text password like that and i will go down our password.setter and i will basically override what is going to be stored as password hash now this time i'm not going to make that to be equal to plain text password besides we are going to use the functionality of the decrypt variable that we have created so i will go to here and i will say from market import b crypt now if you remember this is accessible from the dunder init file because we initialized it over there and now i will go back to our models dot py and i will use some of the functionalities of this b crypt instance so i will remove this for a minute and i will say b crypt dot generate password hash and this generate password hash is probably going to receive a plain text password as an argument so it will be as easy as giving this plain text password as an argument to this function or to this method excuse me so now as we have done that then i like to apply some decoding in here so it will be just dot decode and we will use the utf-8 to decode this generated password hash okay so once we have set this then we should go to our routes.py and take some additional changes in there because if you remember in our entire project the only code that is responsible to create instances of that user is actually the route dot py so i will go to here and right under our register page if you remember we set our password underscore hash to a plain text password now the only thing that i have to do here is basically besides giving the password hash argument is giving the password argument so this will be responsible to complete the entire process of storing passwords as hashed passwords because we set our password and this line of code goes inside the password dot setter because we set a new password to a new user and then this line of code is getting executed and this is exactly what we need because we storing enhanced password so this is the process and we want to test this up actually in the next user that we are going to register so i will go to our terminal and i will say clean the screen again and we will execute python run dot py and once we have this then we can verify this by refreshing our page and going to register and now i will create jsc 2 3 because we had jst2 and we will set a valid email and now i want to prove you that we are using one two six again so i will just cut this out from here and paste this in twice and once we create an account then the results are quite great but now to actually verify this i'd like to show you the results from the gui that we use so we can go to here and we can basically refresh that out by pressing f5 and now you can see that we have a hashed password for the jsc 3 users so this is exactly what we wanted to achieve by using the getter and the setter to differentiate between what happens when we do each one of them all right so now that we have secured our passwords it is about time to start working on the way that we can log in our users now currently we will start by designing what is required to basically display a login page successfully to our users so it will mostly require the steps that we probably have done until now so we will create a login form within our forms.py and for sure we will set up a new route and we will create a separator template for that so let's go ahead and start working on this okay so i will go to our route dot py as you see i'm already here and we can basically start working on the same process like we have done to design our register page so i will zoom in here to make the font bigger so we will start by saying at app dot route and we want to send our users to forward slash login and we want to allow the methods of get and post like we have done in the register page so it will be get and then post like we did previously and then we can basically name it login page and we can go inside our function now i want this to be more centralized so excuse me for pressing enter a lot of time and now in here we will just start by returning a render template and we will send our users to login.html like that okay so let's go ahead and create this template as we did not create it yet so it will be just as easy as going here and create the html file and we will name it login we will delete the auto-generated html now i will rely on the register.html to kind of help us a little bit so i will open the register.html and i will copy everything from here and i will paste this in in the login.html and now i want to delete everything that is under our body text so i will just minimize the div class container and i will just delete everything that is right here and there we go we only left with the body so i will also change that to login page it makes a lot of sense and i will test our results out so we will go to our website and we will go to slash login and you can see that we are inside a blank new page so everything works well now if you remember in the navigation bar as you see the register works because i clicked on it but the login page is not working so let's go ahead and fix that quickly so i will go to our pycharm and it should be inside our base.html and we should go down and we should identify this line in the login style so this is right here and we can basically copy the url underscore 4. so you should already be familiar with this function and we should paste this in right here in the href of the login and we should change this to login underscore page because this is the name of our route so now that we have done this we can test the changes from clicking here and let's refresh the page to changes to take effect so i will go to home i will click login and you can see that everything works fine okay so once we have done that then let's start working on our forms so it makes sense to go to our forms dot py and basically create one new form like we did for the registration so it will be as easy as going to our forums dot py and start working on a new class but this time we are not going to create all the fields like in here basically to log in our users we only require to have username and the password and for sure the submit field to take some actions so i will go down here and i will start creating a new class so it will be class login form and this will inherit from the flask form as well and we will go inside our login form and we will start saying username equals to string field and the label that we're going to give here is going to be just user name like that and the only validation that i like to create here is the data required so i will say validators equals to a new list and inside that i will initialize the data required and i will close the instance of this class by adding parentheses now the same approach will go for the password as well so i will allow myself to copy everything from the username and paste this in and change this to password and change this string field to password fill and change the label to password and delete the name and this is fine to leave it in here and the last action will be to submit so now i will also allow myself to copy that from the registration form and paste this in and the label for that will be something like sign in and this should be fine for creating our login form okay so once we have done that let's go ahead to our routes.py and create an instance of this login form so i will start first by importing it right here in the market.forms line so i will say login form and i will go here and right before our render template i will say form equals to login form and i will close the parentheses and now i can basically use here form equals to form exactly like we do in the registration page as well so once we have sent the information of the form then it is a great idea to go to our login.html and customize this html page now again since we pretty much implemented this html logic in our registration form and actually to save us a little bit of time then i already have created this form html tag so you can find this code snippet in my website by easily going to part 11 of the flask series and search for a code snippet that is going to be named login form and also make sure that you paste this in under the body class text center like we have in here and i'm going to paste the form tag and let's actually go over what is going on here so the first here is the div with class of container and if you remember this is responsible to centralize our information from being this wide to something like that okay so this is containing the information inside of it and here we have our form tag with the class of form dash sign in and right under it we have the hidden tag which is necessary for generating the csrf token so you should be familiar with this because we covered this in the registration part and in here we have a header with please login and an image with the logo of our website and in here we basically use the ginger syntax to grab the fields of username and the password and once we have done that then we have a breaker line that is separating our field from the next html information now right above the submit in here we have something new that we did not see before so this is the div and inside here we have a text do not have an account so i decided to create this just because to allow our users to go back easily to the register page if they don't have an account so you can identify this by seeing the href with the anchor tag and you can see that it leads our users to the url of register page so let's actually see this in action so i will go to our website and i will log in and now you can see that we have the username field and we have the password field and we also have the do not have an account and we have a button that says register now if i click on it then you can see that it leads us back to the register page now functionality like this could be also a lot nicer if we have implemented it in the register page so i'm going to do that just in a second so we will go to our python and we will easily grab this code snippet from here and we will paste this in inside our register.html so i just opened our register.html temporarily and i'm going to go as we did in the login page and i'm going to paste this in right above the forum dot submit and that time i will say already have an account like that and i will lead our users to login page and it makes totally sense to change the text in here as well so once we have done that then we will see the same result in the register page as well so if we click in here then you can see that it leads us back to login page okay so just to memorize what we have done until now well probably we want to complete the functionality of that sign in button because we don't do anything special when we click on the sign in and we want to throw some errors if there are some wrong information and we want to proceed our users to the market page when the login is successful so it is going to be a lot of stuff that we have to configure on our back side of the application so first of first we will start by installing the library that will allow us to manage our login system easily with flask so it will be basically going to our web application and saying here pip install flask underscore login and once i have done that then you can see that everything is fine and i can clean my screen and now we can continue to pycharm and start working on importing this library so the library itself is like a login manager for your entire application so it has to recognize which flask application you want to manage the login system with so this is why we are going to start importing it from the dunder init file so we will say from flask underscore login import login manager like that great and once we have done that then we can say right here login underscore manager equals to login manager so we will start an instance of that and we will pass the application as the argument so nothing is different than the sql alchemy or the pcrypt that we have done previously throughout this tutorial all right so once we have done this we are ready to work on our login route to really write the functionality of what happens when your clients are going to click on sign in so we will go to our routes dot py and we will navigate to our login underscore page and we are going to pretty much apply the same logic like we did in our register page so if you remember we used to call this conditional if formed validate on submit and then if this conditional hits true then we are going to take several actions so it might be a great idea to start with that okay so i will say in our login page so we will zoom in here and we will say if forum dot validate on submit now if you don't remember this actually runs two functions behind the scenes and the first is to validate that all the information is valid and it also going to hit this conditional when we click on that submit button that we have created for our login form so i will go inside our form and now we are ready to pretty much verify if our users have provided a great information so this means that when we put in some information like username and password there are going to be two important steps that we want to verify and the first will be if the user is exist and the second one if the user is exists then if the password is actually the correct password of that user so the implementation of that in python will be like the following so we can say attempted underscore user equals to user dot query dot get and we want to receive only one user object and in here i'm going to provide the data that is filled in the form so we will say form dot username dot data so again this entire statement is going to filter out the user by the provided username but if you remember in that case we should execute that dot first method to really grab the object of the user now if attempted user is none then we can say that the client is providing some wrong information about its username so we can write a conditional and say if attempted user and that will be enough to test out if this is filled with some information and not none now sorry for deleting that this is not enough to really log in our users because now we should check if the password matches the user that tries to sign in but if you remember we store our passwords as hash passwords so we kind of ask ourselves how we are going to check if the user from the form matches the user from the database so it is never going to be match because the password we store is a hash password and the password that the client fills in is a regular string of password so to overcome this we can basically use some functionality that we have inside the bcrip library that is going to help us to verify that the passwords are match so now i want to stop writing this conditional in here and go to our modules.py and start working on some function that could be accessible from each user object that is going to really help us to overcome the problem that i specified so i will go down here and i will zoom in a little bit so we can see better and i will start writing a function and we can say check password correction and this is going to receive the self as a parameter and also it is going to receive the attempted password to really grab the password that is filled in within the form so in here we can say if b crypt dot check password hash and now this function is going to accept two arguments it is going to first accept the password that is hashed and then the password that is going to be filled in from the form so we can put in here self.password hash and as the second argument we can say attempted password now this entire statement here is going to return true or false so if we actually hit this conditional we can return true and to actually make this a little bit more efficient we can do something like the following now since this entire statement here is going to return us true or false then we can basically avoid using the if statement in here and we can basically return whatever this statement is going to return so if i change this to return then basically what i'm saying is execute this function and return its value back when we call the check password collection so this is going to return us either true or false so once we have done that then basically we can go to our routes dot py now you can remember how the attempted user is going to be stored within a user object if this entire statement is going to return a user object or not so i can continue my conditional by saying and attempted user dot check password correction so basically i am calling the function that we excuse me the method that we wrote inside our user module and now i can close this in and if you remember this function received the attempted password as a parameter so we can say attempted password and i will continue on from here and we will say form dot password dot data and this should be enough to really write this long conditional now i'm going to write in this in splitted lines because it doesn't look a lot friendly so i can basically go with something like this and no not like that but we can divide that and that okay so now things look a lot better so this entire thing is actually a one long if statement but this is required because of the explanation that i made in the previous minutes okay so once we hit this conditional then we can really start logging our users now we are going to use a built-in function that is already existing inside the library that we installed previously so let's go ahead and import this in our routes dot py so we can say from flask underscore login import login underscore user and this should be enough for now we are going to import more stuff from this flask login in the future and i will scroll down back to our login page route and now we can call this function like that and we can provide as the argument the user object that we want to log in so it will be attempted user and this should be enough to really log in our users now we probably want to provide some extra information to our clients when they have logged in successfully so we could say flash so if you remember not flask but flash if you remember the flash is the built-in function that is going to help us to provide extra messages for our users when some important thing happens and we can type in a message like success and we can say you are logged in as and now we can really give the username that is logged in so we can turn this into a formatted swing and we can say attempted user dot username now again if we are going to hit this conditional then it means that the attempted user is not none so this is why i can access this attribute so it is fine doing this and once we have done that then we want to probably direct our users to the market page to start buying some products so it will be basically return redirect and we can call it and we can call the url underscore for built-in function and if you remember this function is going to receive as the argument the name of the route that you want to redirect your users so if you remember we have a route that we called market page so i will copy its name and paste it in over here and once we have done this then basically it is a great idea to really finish up what happens if we don't hit this long conditional in here so we want to write the else statement for that so i will say else and in that case i want to raise a message like this so we can say username and password are not match please try again something like that and i just remembered that i did not put in some categories to our flash messages so obviously we want to provide here category equals to success like that and this is for the conditional that we hit so if we were able to log in and this one should be category equals to danger so danger is what going to help us to display a red colored message because it is going to be translated in our base template if you remember to a danger message so this is why we have to provide this danger as it is okay so this should be enough to test for the first time if we can log in our users so we can go now to our web browser and we can refresh our login page but we did not verify if our website is running so we should go and execute python run.py and once we have done that then we can go to here and see some exception that i really wanted to see and so we can solve this together now this is actually a perfect example for an exception where you really want to carefully read what exception is about and provide some extra steps to really complete this login system successfully so you can see that it saves us exception missing user underscore loader or request underscore loader so we should refer to this documentation and see how it works so we will copy this and we will paste this in here and we can really start looking of what this documentation is about so we can see that there is some message that says how the flask login works and you can also see that we will need to provide a user loader callback to really make our flask application to understand that if we navigate from different pages when we are authenticated then each refresh there is a different request session that the flask application has to understand if the user is logged in or not so this is why we have this decorated function in here that needs to be executed every time we load some different page so we should copy this and paste this in inside our modules dot py and this is why i will grab this entire code from here and paste this in inside our modules dot py right here so once we have done that then it is also a great idea to import this login manager that i talked about so now you really can understand why we created this login manager instance in the beginning of this video so i have done this for this exact step that we should provide later on so i will go here and i will say login manager like that okay so before we continue i'd like to add a personal correction to that line because i remember myself when i developed the project that we are working on this tutorial then this wasn't the return statement so i'd like to change this a little bit to something like query dot get and in here we will convert the received user id to an integer before we really try to get this user so i will say user id right between the built-in in function and this should be enough now if i quickly go back to our documentation then we can also see some more instructions about how to make this login system to work now you can see that we have to provide some extra methods to our user module so you can see that we have to hard code this method that method and as well as those two in here so this really should mean that we have to go ahead and write those methods in our user model because this is what flask requires us to do but to really overcome this i already know a class that is already going to provide those methods to be accessible within our user model so what that means it means that we need to inherit from some additional class that this class will automatically include those methods so let's go ahead and see how we can do that so i will go back to our modules.py and i will say here so it will be from flask underscore login import user mix in now this class is going to include all the methods that we saw in the documentation and to really prove my point i will allow myself to go inside this class by pressing the combination of control b if you use visual code then this should be f12 or in any id you use just make sure how you can inspect to your classes so if we go here then you can see that this user mixing class already includes the is active is authenticated is anonymous and e and get id so this should be enough to inherit from this class in our user model so i will say here comma and i will write user mixing so this really saves us a lot of time to really go ahead and hard code some four methods that the flask asks us to do so it is enough to add it as an additional class that we want to inherit from okay so once we have done that then we can really go ahead and test for another time if we can log in our users so i will go to our terminal and check if our website is up and running and it is so it is a great idea to go back here and go to our homepage for a minute and now go back to our login and now we will try to login by the latest user that we created so it will be jc3 if i remember correctly and we can say the password as one to six because this was the password and now if i click on sign in then we receive this non-type object has no attribute first so this means that we wrote something wrong in our query.get inside our rouse.py and i think we should fix this by using some another method after the user.query so i will go here and we will close the mixins it is not necessary now and we will go to our routes.py now i will allow myself to ignore these warnings in here basically this happens because we inherited from some another class right now and it thinks that these arguments are now not accessible or something like that so i will ignore that because this is not going to affect the registration and the exception was in that line so i think we should change this to filter on the score by and one other wow another wrong thing that i have done here is i did not provide the key that i want to filter out from so excuse me really for mismatching the filter on the score by with the get function basically i'm doing this because it is working in another way in django the other framework of python so this should really be enough to go ahead and log in our users so let's test this out one more time okay we will go to home and we will click on login and we will right here jstree and we will try to sign in and you can see that now our user is logged in and we see this success message that we can also close when we want okay so the final customization left to really close this login system topic is really giving our navigation bar a little bit more styling because now our users is logged in so we really want to avoid to show the users the options of login and register and we probably want to show stuff like log out or some extra information that the current logged in user should see so let's go ahead and start doing this all right everyone so right now i'm inside our base.html that we have created for the template inheritance way a long time ago now i'm going to take a lot of changes in here because we want to differentiate between the options that we show to our users whether if they are logged in or not so to do this we can basically go down and we can start writing some conditions with the ginger syntax so for example we'd like to check if the user is logged in or not and if the user is logged in then we probably want to show another information rather than log in and register so let's go ahead and start implementing this so we always want to display this home and market options to our users so i will leave that and i will start writing a conditional right here so we will start saying so curly brackets and then presented sign and we will start writing and if condition if current underscore user now you might be confused how we can access this variable and what this is about so if i go to our router.py i said that this flask login is going to have a lot of built-in functions that is going to help throughout this session of creating the login system so this flask login includes a function that knows to grab the current user whether if the user is anonymous user or if it is actually a logged-in user so this is why i can access it from our base.html so i will say in base.html current user dot is underscore authenticated like that and if you remember this is a method that is arriving from the user mixing that we have inherited so now once i have done that then we will type in else like this and we will also say and if like that and now we can move our different nav elements between the if current user is authenticated and also some of them inside the else statement right here so if the user is authenticated then we probably don't want to display the login and the register navigation elements but if the user is not authenticated then we want to display them so it is a great idea to copy this entire thing from here actually to cut it and paste this in between the else statement right here so now i will fix the navigation i mean the indentation in here and this is great and once we have done that then we probably want to display a nice output like welcome and then comma and then write in the user's username and also we want to display one more element that will allow our users to log out now i'm going to configure the functionality of the logout very soon so don't worry about that okay so i will copy this entire thing from here and paste this in here and now we can work on customizing our navigation elements now if you remember this li tag is actually a one navigation so i can just delete one of them and as a beginner we can say here log out and i will just delete everything from the href and add here an aztec sign to really not send our users to anywhere if they click here because we don't have currently the functionality of the log out and the other thing that i want to do here is copying this again and paste this in over here and the next thing that i will provide here is something like the following so it will be welcome and we will add a comma and then we will use ginger syntax to refer to the username of the currently authenticated user so it will be user i mean current underscore user dot username and i think we can delete this href attribute from here so it really doesn't need this href attribute and this should be enough now the reason i left this in here is is because we are going to add an href in the future and this is never going to send our users to anywhere so i'm fine with this approach okay so i will go to our website and refresh it out and you can see that we receive here welcome jsc3 and we have the option of logout that doesn't send our users to anywhere so this is great now one other thing that i'd like to do here is adding the budget of our users in a nice colored way so i will allow myself to copy one of those in here and paste this in right above it and take some different actions in here so between our anchor tags we really want to delete this welcome message and we want to hit enter now if you remember from the very beginning of this tutorial i said that there are a lot of styling frameworks that does some job to really make our lives easier to import from some already designed styling now we also have one of those to use different icons now it could be a lot nicer if we will display an icon of a coins or something like that for our users so the user can really understand that this is his budget so we can do this by calling the i tag like this and we can say class equals to f a s f a dash coins and now we can say between those something like current underscore user dot budget because if you remember this is the attribute that returns back the budget of our users now i'd like to give this a little bit more styling now i also want to add some styling to our anchor tag so i will go here and i will say style equals to something like color equals to long green so i already know that this is a nice way to display the color of green and i also like to display this entire thing here between the anchor tags as a ball text so we can do that by font dash weight and column and we can say bold and this should be enough to really display some nice information to our users about their budget so we can go now to here and we can refresh and you can see that we have the icon of coins and we also have the number right here now i see that the aligning could be better in here so let's see what i have done wrong and i think this is the fact that i put the text between the eye tags so we should cut this from here and go down a line and locate it over here so this should be a little bit better now and now if i refresh our page then you can see that the aligning is quite great now we could also go here and display a comma if the budget is going to be higher than a thousand because this is not the standard way to really display a number so if we will have a user with a six digit of a budget then you will see a text like this so i will show you that here you will see a coin like this so we should write a function that is going to add a comma every time that we have larger than four digits and also it should be located from the fourth position starting from right so we can do this by going back to our project and we can go to our modules.py and we can write here some more property that is going to be responsible to display our budget a little bit more pretty so we can say add property in user and we can say here def prettier budget like that and we can receive the self as a parameter and the way that we can implement this is first of first check if the budget includes four digits or more so we can say if length of the string version of our self.budget is actually greater or equal to four now the logic implementation of this case is not going to be easy so i will allow myself currently to say pass here and i will also say else in here and if this is actually not greater or equal to 4 then i can basically return the value itself so this should be return and we will add the f for formatted string and we can say self dot budget and right after it we can add the dollar sign okay so i think i close this by mistake let's open it back and now i want to show you how we can really work on displaying comma only in the fourth position starting from the right so to explain this i will open our terminal and i will clean the screen and enter inside python okay so let's say that we have a number and we will call it p and this should be equal to 1000 and now i want to say that we should convert this into a string okay so this should return us a thousand with a single quotes right here and so now if i go here and index the character at the -3 position it will start counting from right till it reaches the index of three so this is minus one this is minus two and this is minus three so if i grab this then this gives us back the zero now i always want to add a comma only after we reach the third digit starting from the right so this is why i can go with something like the following so that time i will display the value of str p and then we will index it by -3 and then we add a column to really display all the elements right after the -3 position so this should be responsible to display all the zeros and so if we could say something like the following so for example let's give a right now and we can add a formatted string and we can wrap those with the curly brackets and now i can add a comma now you can see if i print a then we kind of starting to reach the behavior that we want to reach so once we reached this stage then we should look for a way to grab all the digits and we want to stop at the -3 position so this is also going to be a little bit complex but now i can say here so we will add more one more curly bracket and now we will call the strp again so pay attention where i am located in the terminal and now i can index this by the following statement so i could say give me all the digits from the beginning until -3 like that and now if i enter and hit a now you can see that it works for the 1000 itself now to prove my point i could basically overwrite the p by saying 1 000 like that i mean 100 000 and now we could call the exact same statement and print a now you can see that this works as well so this is why i can grab this code from here and copy that out and paste this in right here as a return function like that okay so after it we should change the self.budget with p so this should be something like that and now we can add a dollar sign right here so i know that this was a complex topic but i really wanted to show how i thought when i wanted to done such a task because you could probably pay attention that i prepared to show you how i developed this project and so this was one of the greatest challenges that i had to deal with so i really wanted to make this explanation okay so now we have this dynamic property that its name is prettier underscore budget so we should go back to our base.html and change this current user.budget to paying three tier underscore budget and once we have done this then we can go to our terminal and run our website by saying python run dot py and now our website is up and running and so now we could refresh this page and you could see that now we got the comma right here but this is great because this is going to be dynamic so in the future when i'm going to purchase some items then you could see that this comma is going to be disappeared because of the way that we implemented this property okay so till that point we were able to customize our login system successfully but currently if we press on that log out nothing happens so let's go ahead and start configuring this so the way that we are going to do this is by adding an additional route to our application and then this route will know to log out the logged in user and then we will finish it with redirecting our users back to homepage so we will open our pycharm here and actually i see that i'm inside my base.html and it might be a great idea to show you what i'm going to configure in the future so if you remember then we have this log out anchor tag and then inside here we are going to send our users to that url underscore for so actually if i'm on the base.html then i'm going to do that so i will zoom in and i will basically copy this from here and paste this in to here and i will change this to log out now you are probably asking yourself why you are using this url for logout page although you didn't create the route because now i'm going to create this route okay so we will go to our route dot py and we will go down here don't be don't get too much worried about that we said that this might occur because we inherited from some another class and that is fine so we will go down here and we will say at app.route and actually let's zoom in a little bit and we will send our users to slash log out like that and then we will say def log out underscore page and then inside of it we have to use a built-in function that is already inside the flask framework that will allow us to log out the current existing users so in order to do that i will scroll up here i will import the log out underscore user built in function from here and actually once we imported this then we can scroll down and use the function like log out underscore user and that is actually it okay so this will be enough to grab the current logged in user and log it out okay so this should be enough and the next step is probably the flash message that we want to raise here because once we log out our users it totally makes sense to display a nice alert to our users so the user could be basically aware that he is logged out so we could say flash and then we could say you have been logged out like that and actually it is a better idea to send its category as info because it just looks nicer in blue when we log out users rather than just green color okay so this is actually an informative message that we want to display and it totally makes sense to redirect our users back to home page once the user is logged out okay so we will say return re direct and we will use the url for and we will say home underscore page now again the home underscore page comes from here okay so our users will come to here once they are logged out now we can actually save this out and already test this because if you remember we configured as well as the button of log out on our navigation bar so i will go to our website and i will refresh our website and it totally makes sense to check if it is up and running so we will do that so once our website is up and running and then you can see that our user is currently logged in and you can see it from this message now if i click on log out then you can see that we are back on our home page and then there is an informative message that says us you have been logged out so everything works perfect okay so i think that our customization about the market page is pretty much finished because now we have all our navigation elements functioning correctly but currently i'm not quite satisfied with how our home page looks like so it could have been a lot nicer if we had our logo on that home page and as well as a button that says get started or something like that now i already have an html code that is ready to display such an home page so let's go ahead and paste this in in our home.html and as usual you can grab this home snippet from our website only thing you will have to do is going to part 13 of my flask course from my website so let's go back to our pycharm and find the home.html template and actually i'm going to delete everything from here and i'm going to paste this in now let's have a quick look what is going on here now here we extend the base.html we already know how to do that and we also have the welcome to gymshare coding market message wrapped around the blog title because we want to customize our tab name and in the blog content we have some elements that customizing the image that we want to display if you remember this is our logo of our website and this is arriving from this big div tag now in here we also display some nice h1 text and inside here we have a paragraph that says start purchasing products by clicking the link below now the link below is this line so this line is an anchor tag with a button of class button dash primary you already know that from our previous episodes as we created this kind of button when we register or log in our users and you can see that it takes our users to the market page if they click on get started so this is actually something that should be pretty enough for the for the most basic home page for any website so if i save this and go back to our home.html and refresh that out then you can see that we have a nice home kind of a banner that really shows that this is our homepage now if i click on get started you can already see that it leads us to the market page thanks to that url for market page that is inside that angle tag now here we actually have some problem that you already maybe paid attention or not now you can see how currently the user that is using this website is not logged in so we probably ask ourselves if we want to take our users to the market page if the user is not logged in well i think that this is something that we can customize so we probably want to avoid from our users to see that page if they are not logged in so it totally makes sense if they are trying to click on get started and then it will lead them to the login page first and then if the login has been completed successfully then it will take them back to the market page like it's supposed to so we actually have a built-in function for that as well so let's go ahead to pycharm and see how we can use it okay so we will go to our pycharm and we will go inside our routes dot py and we will import this function that will be responsible to not take our users to that market page if the user is not logged in so it will be as easy as going to that from flask underscore login line and say login underscore required okay so once we import this then we can use it as a decorator now if you remember from the very beginning of this entire tutorial i said that the decorators are like functions that execute before the actual function itself so there is a reason why we put in app.route because we want to execute this functionality before we create the route itself so the same approach goes to login required we could actually use this function as a decorator right before our market underscore page route executes so it will be app.route slash market and then right after it we could basically say login underscore required so it will be something like okay we are going to that market page so this line executes and then this line executes so this line will be responsible to take our users automatically to the login page now let's actually see if only adding this line is enough to complete our functionality so i will save that file and i will go to our website and i will click on home and then i will click again on our get started and you can see that we receive an unauthorized message here that says us the server could not verify that you are authorized to access the url that is requested now this is fine but we would like to display the login page automatically if we require our users to log in before accessing this page so we actually have to say to our application where is that login page located so i can redirect the user that wants to log in so it totally makes sense because if you take a look in that login required decorator we actually do not provide any extra information about where it should send our users so to configure this up we should go to our underscore init.py file and we should specify to our login underscore manager where is the login route actually located so once we go down here and we say login underscore manager dot login underscore view equals to and this actually expects for the name as a string of our login route so if we take a look if you remember this is how we named our login route so i will copy the name of the function and i will paste this in between those double quotes so now that we have added this this should be enough to redirect our users to the login page before the market page so let's test this out okay i will go back to home and i will go to get started and now you can see that it already leads us to the login page now you could pay attention that it shows us the alert not in the nicest way but we will solve that in a minute but i actually want you to take a closer look to what's going on in the url bar in here now you can see that we see the slash login but we see a syntax of query with a question mark that says us that the next url from here will be market so you can understand this from this html expression in here so this means that everything is actually working properly now let's fix this alert in here so we probably want to specify to that login manager how we want to display a flashed message because when we use the built-in login required it automatically takes responsibility to flash a message so we want to give it a category so it can understand to display this in a blue color or something like that so i will go back to our dunder init file and right under this line i will say login manager dot login message category and you can already see that it is a built-in field that i can fill in so this will be equal to info because we probably want to display this in a blue color so once we save this then we can test this out again so we can go back to home and again click on get started and now you can see that it really works like we expect okay so we see our regular flashed messages like we used to see when we try to login log out or register okay so now i can basically try to log in with a random user that already exists so we will try to log in with that gst4 user and i will click on sign in and now everything is back and works properly so this is a really great addition to our website because this way our clients could not access this slash market page unless if they are logged in already now i'd also like to show you the behavior when we try to register to that website very quick so let's try to create an account with jc6 and we will specify a valid mail like that and we will type a basic password and now if we click on create account then you can see that it created this account and it already shows us that please login to access this page now you can see that it tries to lead the created account to the market page as well but it requires the currently registered user to login now it could have been a lot nicer if we raised a message that the user is created successfully and then already log in that user so this is something we probably wanted to do a lot earlier than right now but let's actually do that okay so we will go to pycharm and i'm already in my route dot py now i want you to take a look right in here so actually in the part that we try to redirect our users to the market page it could have been a lot nicer if we do those two things here so first we'd like to flash a new message and also we'd like to log in our users so we can already see the market page as a new user so i will grab those two lines from our login route so i will copy those and i will go back and paste this in right here now in the argument let's actually delete the entire message from here great now as the argument of the login user we could basically pass in the user object that is user to create so we can say user underscore 2 underscore great now if nothing goes wrong with those two lines then it means that the user has been created successfully so we can log in that user now once we do this then we can type in a message like the following so it will be let's write in a formatted string here and we can say account created successfully and we can say you are now logged in as and we can say user to create dot username like that okay so let's test this out with another user that we probably want to create now now i forgot to specify the category so excuse me for that and it is a great idea to actually go ahead and say category equals to success exactly like that okay so now we can go here and we can try to register again so we will create the jsc 7 that time and we will try to create the we will try to fill in valid information so we can click on create account and now you can see that we are already in the slash market and it saves us that we are logged in as jsc 7 so it is a lot better now because the new clients that are going to register to that website are going to have a lot better experience with this approach okay so if we take a closer look on how our market page is displayed to our users we'd actually like to change this display a little bit and the way that we want to do this probably a one way that we can do that is to divide this page into two main sections and then the first part of this page is going to be responsible to display the available items on the market and the other part is going to be responsible to show the items that i already purchased as a user from the market so it could have been a lot nicer if we had a division where we display all the items in the left pane and the purchase items in the right pane so it is going to be more focus page about the entire website itself so the way that we can do this is by grading system of the bootstrap styling framework so let's have a look in the bootstrap documentation so i will go to here and i'm inside the greeting system documentation of bootstrap now you can see that we have several examples how we can divide our page now i'd like to show this section in here so this section includes a div tag and it says that class equals to row now the grading system could be implemented the second that you create a div tag with a class of row because it is just as it is sounds because it is going to create a row that is going to be expanded to the entire page so we could grab the row that is created and we could customize the way that we'd like to divide it so the way that this could be divided is by creating some call tags i mean column inside this div class equals to row so the second that you see this and this this is going to be responsible to align our html pages in the following way so we could already start imagining this because in the call dash 8 area we are going to display the available items on our market and on the call dash 4 area we are going to display the purchased items so let's go ahead and start implementing this and if you did not understand what i explained then it is fine you probably will get it as we will start implementing this on our real website so i will allow myself to copy this code statement from here and paste this in right under our block content like that okay so let's fix the indentation a little bit and then we are good to go so the second that i do this then let's see the results what is going to look like so i will allow myself to refresh our website and then you can see the alignment okay this is exactly what we want so we are going to grab our entire table and we are going to locate it right where the call dash 8 starts so let's go back to our pycharm and actually i will allow myself to cut this entire table from here and paste this in under our call dash 8 div tag so we will delete this text from here and we will click on enter and we will basically paste our table now i know that the indentation is quite ugly but i'm going to fix that with a pretty fire just in a second so if we save that and go and see the results of that then you can see that this is perfect and this is exactly what we want because the available items are exactly on the left pane now we'd also like to give some spacing to that table so i will create some more styling elements to that row so our table will have a little bit more spacing starting from the left and also from the top so let's go back and do this so i will start writing right where our div class row is something like style equals to margin dash top then add a column and then we could say 20 pixels so we'd like to give a spacing of 20 pixels and we could do the exact same thing for margin dash left and we will say 20 pixels as well now this is going to be responsible to show the table i mean the division of the grading system in that way and i think this looks a lot cleaner right now okay so i said that we like to fix the indentation now you got a couple of ways to do that you can install some plugin to pycharm that is going to customize the annotation automatically for you but you could also basically search for an html prettifier in the web browser so it will be as easy as going to google chrome and search for something like html freetifier and we could go and click on the first result and we could grab our code and we could paste this in and we could click on format html and this will be responsible to already customize the indentation for us so you could click the copy to clipboard section and go back to pycharm and paste this back in and we are good to go okay so you got a lot of ways of how you can do this so i like this approach as well but you can definitely go ahead and install some plug-in to your pycharm or if you use another idea like visual code there are a lot of plugins for those kind of stuff all right so let's continue implementing the logic of the buttons that we like to give their functionality now to avoid actually confusions and to remember for the future i like to give the call dash for name something else so we could say here owned items something like that and we call fix here the div tags like this as well so it will be easier to remember in the future that we like to implement here the owned items with some ginger syntax as well okay so if we scroll up here then you can see that we don't got any title that describes what the left pane is about so it could have been a lot nicer if we would go right above the table tag and we could write in some h2 tags for example and we will close those tags and we could say available items on the market something like that so it will be a lot easier for the users to catch up what the left pane of our page is about now further than that we could also add one more paragraph in here that says click on one of the items to start buying okay so something like that could be a nice secondary title as well and we should write here lower i so it makes a lot more sense and i'd actually like to add some more br tags in here to really see how it affects the entire page so let's see the result of that and you can totally see that it looks a lot cleaner on our eyes when we look at it we can really understand what the left pane is about and we could really do the exact same steps in the right pane where we'd like to display the owned items so we could basically go back to pycharm and copy those lines and paste this in right here so we could say in here let's change the text to own items like that and we could say click on cell item to put an item back on the market something like that okay so the results of that would be something like the following so i'm just thinking the indentation and if we go back to the market page then we can see that now the items page are totally fine and we could continue on implementing the logic behind those buttons okay so now i'm inside the bootstrap documentation again and i'd like to show you some of the nicest features that the bootstrap styling framework gives us so we have something in bootstrap that is called models now this is not the models like we see in the flask itself okay so models allows us to kind of display a nice new output to our users and it totally focuses us to really look at the new output that appears to us because it graze the entire background of the webpage so let's actually see a demo of that so we have this html code in here which is basically responsible to display the model that i'm talking about and basically this model could be configured as a behind-the-scenes functionality of what happens when we click on a button so when we click on launch demo model in here then you can see the result of that so this is exactly what we like to do when we want to display some more information about each one of our items and the exact same process is going to be like displaying an ensuring form if we are sure that we want to purchase that item so this is perfectly what we need for our website now the way that we can implement this on our site is probably the exact same steps like creating an html code that is quite similar to that and then we could connect our buttons with that modal now to actually save us a little bit of time i already customized a nice looking model for us so let's go ahead and see how we can do this on our itunes html okay so i'm back inside our market.html file now if you remember from the demonstration that we saw previously that the button and the modal element that was faded out are actually located in the same code snippet so what this means it means that the modal and the button itself should be located in the same html file but actually pasting the modal itself in this market.html file could be very confusing because it is going to be a lot of lines of html code in this market.html and this is just not organized and could lead to misunderstanding what each html code is responsible for so to avoid this we could locate our model in a separated html template and then this market.html could import this model that we want to create now the way that is going to be designed it is by creating one more directory that we will name it includes and within that includes directory that we are going to create we are going to create some html files that are going to be like helper files so we could import the code snippet from each one of them now let's go ahead and do that okay so i will go inside our templates directory and we will create a new directory and we will name it includes now once we have done that then we can create a html file inside that includes directory that we have created and we'd like to name it items underscore models like that and let's actually delete the auto-generated html from here and in here i'm going to paste the model that i talked about to really save us some time so if we paste this in then this is how the modal looks like when it comes to implementing this in html now i want to give a short overview about what this html code is about so you can see that we have this div tag and then we have a class that says modal fade so this is going to be faded and this is the identifier takes from here now we are going to use it in the future so this attribute is actually quite important for us and we can also see that we have some h5 tag inside our model content and i said that the title is actually goes here and we also see that we have a class with modal body and here we are going to display the actual information that we'd like to display in the body of the model okay so this is pretty much the important sections of what this model is about now the way that this could be imported in the market.html is by using the ginger syntax so if we go to here then we could basically import it let's say that we want to import this in here now we could say something like the following so i will zoom in a little bit and we could say include and we will open a single code here and then we want to give the location of that html file that we'd like to include so it is going to be includes four slash items underscore models dot html like that okay so once we have done this then it is basically going to use the code from here and located inside this market.html now to explain the next topic that i'm going to talk about i'd like to divide the display here so i will go to window and edit all tabs and select split vertically okay so in the left pane we have our items modals and in the right pane we have the market.html so let's zoom in here and as well as let's go here to the button of more info now if i now go to our web browser and refresh our page and click on more info then you can see that nothing happens and the reason that nothing happens it is basically because this button doesn't know which model it should trigger so we should specify some more attributes to that button so let's go to our pycharm and right in here so i'm going to scroll a bit and right where our more info button is i am going to specify some html attributes that are quite important for this trigger to work so i will say data dash toggle equals to modal like that and i'm going to scroll here a little bit more and zoom in so we can all see and right after it i'm also going to say data dash target equals to now the value that we'd like to give here is the exact same name of the identifier of the model that we'd like to display so this is why i said previously that this identifier string is going to be quite important for us in the future so i will allow myself to copy this entire string and paste this in right inside our data target now we should also include the hashtag sign to really specify correctly the target that is going to basically displayed when we click on that button okay so now we can allow ourselves to test this out so i will go to our page and if we refresh that out and click on more info then you can see that we can see our model and this is quite great now we can also see if we click on the other more info because it is implemented for both of the buttons now you could pay attention that the background of this model is white and we probably want to change it to really make it fit to our entire website so the way that we can do that is going to our items dot models which is right there and write in some more styling that will be responsible to customize the background color for the background color that we want so we will create some style tags and inside that style tags i will say dot model dash content and i will open a curly brackets in here and inside that i can say background color is going to be equal to the hexadecimal value of our background color so it will be two one two one two one like that okay so we can save this out and refresh our page with f5 now if the regular refresh doesn't work for you sometimes the combination of control f5 is a stronger refresh so it also loads the entire styling again so i recommend you to do that if the regular refresh is not working for you so i will do that as well and if i click now on more info then you can see that it is implemented correctly and we can also see the title unlike the previous result and the reason we did not see this before it is basically because the title color was also white so we could not see that and now it looks a lot better than the previous result all right so now i want to solve some important problem that we have on the website now i will open this from here and we want to display the button itself right here okay so if you paid attention in the website itself we saw that if we click on more info no matter which item is then we see the exact same information now we probably look for a way to change this behavior because we want to show different paragraphs for each of our items so what this means it means that our modals should be unique per item so the way that we can implement the logic that i talked about is by the following way so let's go back to our pycharm and see that okay so right here you can see that we have an iteration with a for loop that is right inside our market.html and this is why we see the different items now you can see that our button is targeting to the model more info so it is always going to pull that model itself and it is not going to be unique per item so the way that we can change this is changing the location of where we import that model and actually import it inside our for loop and that way we can customize it to be unique per item so let's go ahead and do that now i will make this market.html bigger for a second and i will grab the code snippet which is include includes items html and i will paste this in right inside our for loop like that okay so now i made the items on the score models a little bit bigger in here and the market is still on the right pane so now that i have completed this step basically what is happening here now is that we start our for loop and then we load our items models html and we do that for each item that we are iterating on so what that means it means that this items underscore modal html is having the access for the item object and i'm talking about this exact variable where my mouse is located at so what this means it means that we can refer to that item right inside our items model.html file so this is quite important because we want to turn our models to be unique per item so we will start by changing the identifier to something like dash and then we will call those ginger brackets and we can say item dash id now by doing this we basically give a unique id for each modal and now we could also do that for the title of our model so we probably want to display the title as the item's name so we could say item dot name like that and we could also say inside our modal body something like the following so we could say item dot description because if you remember we have a description field for each of our items and now this is great and we have completed the customization of the itunes underscore model now i'm going to work on the market.html and if you can remember our data target is now pointing to a wrong location because it should be the same as the identifier string of the model itself so now i will copy this out and i will paste this in like that and now that i have done this then basically we were able to achieve to create models that are unique per item so let's test the result of that okay i'm going to go to our browser and i'm going to refresh that out and now if i click on more info then you can see that we have the title as iphone 10 and we have the description that we have created for the iphone 10 now if i close this and click on more info in the second item then you can see that the title is changing and as well as the description so this is perfect because now we have models that are unique per item okay so now we know that when we click on more info that the result is great but the purchase this item is not configured yet now the entire process for the purchase this item is going to be quite same because all we have to do now is basically creating one new model that is going to be dedicated for purchasing an item and we probably want to display the same model pretty much and this is going to be like a verification model that asks the user if he is sure that he wants to purchase this item so it is also a good opportunity to really understand the entire process that we have done here so this is going to be just basically the same as what we have done with more info so let's go ahead and implement this as well so i will go back to our python and i will make the items models bigger a little bit and we will make the font smaller now you could pay attention that this is the code for the entire model so i can basically copy the exact same code and change the attributes that we have changed in the previous example as well so i will copy the entire code and i will paste this in right here now you can see that this gives us an error because it says us that we have a duplicate id reference now this is great because we probably want to avoid to having the same identifier string so this is why it makes a lot of sense to change this to something like purchase confirm like that and maybe in the title itself we'd like to leave it as the item underscore name but it makes totally sense to go inside our model body and give it here some different text so this could be something like are you sure you want to buy and then we could say item dot name and then we could continue this sentence by saying for and now we can add the price for that item so it will be item.price and if you remember it displays it just as the number itself so we could add a dollar sign and right after it we could include a question mark okay so it is important that we display this sentence in here and i think this is pretty much great for now and only we'd like to change the comment here to something like purchase confirm like that okay so now we have a new identifier that should be implemented for the green button that we have on our website so now we can create the market html bigger and we could change the values for this button so we should also create the same attributes like we did in the previous button as well so we could create data toggle equals to model like that and we could say data dash target equals to and here is again the exact location that i want to paste the value of the identifier so i will paste this in and make sure that you do the exact same thing as well so this is great and now i can save this and go to our website and if we refresh that out then we could basically try to click on purchase this item for iphone 10 and nothing happens so what we have missed let's see that the target okay good mistake so don't forget to add the hashtag sign as well it is quite important so we also have done that for the previous one so it is very important and now if we refresh this page and click on purchase this item then you can see the perfect result that we probably wanted to see so we see the title again and we see the sentence that says are you sure you want to buy iphone 10 for 800 so this is perfect okay this is actually the logic that we wanted to implement from the very beginning and on the next part we are also going to include some more buttons inside this model that are probably going to be responsible to actually buy this item so the close button only closes the model but we'd like to add some more buttons into that model and then if we click on that button then it will make sure that the process of purchasing is going to be implemented for that specific user all right so if we remember previously we wrote the model for purchasing an item now i said that this model is going to lead for an external form that is going to ask us if we are sure that we want to buy this item so to demonstrate that this is exactly what is happening when i click on purchase this item now we'd like to have here one more button that is going to confirm that we want to purchase it so to achieve this we have to create a form and then we have to create inside that form a submit field which is pretty much the exact same thing that we did in login and register but this time the action that we are going to take behind the scenes when we post a request is going to be quite different so let's see how we can do that okay so i will close this and we will go to here and the location that we have to put the form is going to be right here in items on the score of models so if we scroll down a bit then maybe under the question mark i mean the question itself that asks us if we want to buy this item for that amount of price we probably want to create a form so i will just start with creating the tags of it so it will be form and then we will say method equals to post like we did with the login and with the register system now i'm going to stop here and i'm going to create those forms in our forms.html so let's go ahead and see how we can do that so i will go to our forms.py and we will go to here and we will create two new classes now if you remember we said that we want to implement the selling process as well so it is going to be quite same so this is why i'm going to create here two forms so i will start by saying class purchase item form and this is going to inherit from flask form as well and the only thing that i like to create here for this stage will be submit field okay so it will be just the exact same line like we did in register or with login okay so this should be enough now i will scroll up a bit and we will change the label to purchase item okay so now i can copy this class and i could paste this in and we could change this to cell item form so this is something that i already create for the future and we could say cell item like that okay so i think we are done with the forms now there might be some other fields that we might create in the form html itself but actually creating the submit fields in the backend side is pretty much enough for me right now so now i have to send these forms as a context to our templates so if you remember if i open our routes.py then we can totally remember that we send our form instance as an information to our template so i'm going to do the exact same thing with the items.html but we will start first with sending the information of purchase item form okay so it is imported up top here and now i can go just in the first line of our app.route so i will zoom in a little bit and i can say purchase form equals to purchase item form and create an instance of that like this now if you pay attention then we already send the items as an information in this route so we could basically add a comma here and send one more information and we could say purchase form equals to purchase form like that and then this purchase form is going to be accessible from the items.html itself now once we save this then you could remember that this is sent to market.html sorry for saying items.html basically i refer to that html template so if i open the market.html then we have this include in here so what this means it means that we could access the purchase form variable within this template as well so we could go here and in here we could do the actions that i'd like to do right now okay so we said that the purchase underscore form is accessible from here now if you remember from the previous examples of login and register in order to perform a post request successfully we have to create this secure hidden tag that we always initialize so this is why i will go and write a code like the following and now i'd like to give this entire div a little bit nicer customization so to apply this maybe it is a greater idea to move this text here to an h4 tag or h3 track something like that so i just cut this text from here and i'm going to locate it inside our form so i will delete the line here and i will go down here and i will open a new h4 tag for example and we could paste the sentence back in here now we could also say style or class excuse me text dash center and it will centralize the text itself now it is also a great idea to write here even a smaller text than that and to centralize it as well by saying class equals to text center and we could continue on by saying by clicking purchase you will purchase this item so this is a great sentence to write here because the user can totally understand that there is no way to go back if he clicks on purchase this item button okay so once we have wrote those h4 and h6 tags then we can basically continue on with creating the submit field so if you remember the way that we can do that is by calling the ginger syntax and we could refer to that purchase form variable and we could initialize the submit field that we have created previously and now i can give it a class like class equals to and we could say here btn btn-outline dash success so it will give it a green color and we'd like to initialize the button block as well so the entire button will be expanded to the entire form okay so i think this should be enough for now and let's test the results of that okay so i will verify that our website is up and running and it is so it is great and now i can go back to my web browser and close this alert and refresh our page now if i click on purchase this item in here then we can see that we see this nice title and also we see the smaller text that says by clicking purchase you will purchase this item now i pay attention that it might be a great idea to throw some brs in here so we could throw a br in here and we could do the exact same thing in here okay so now let's test the results of that and i think now it looks a lot cleaner so let's continue from here okay so we do not do anything special when we click on purchase item right after we enter the modal so let's see what we have to do when we click on it so if we actually go to our pycharm then i am already inside the routes.py and you can see that we initialize this purchase underscore forum now regularly we would like to go with the approach that we have done for the login and the register forms as well so we probably want to run such a code which is going to be like purchase form dot validate on submit okay so it is going to be exactly the same thing but let's not forget the if statement in here so now everything works fine now before we actually continue on writing some more code within this conditional i'd like to show you how the purchase form looks like when we print it on the server side so if we actually go ahead and do only print purchase form when we click on purchase item let's see the results first so you can understand the following things that i'm going to do right after it okay so once we have done with this then it is a great idea to go to our website and make sure that it is up and running and maybe it might be a better idea if we restart it great okay so now i will refresh our page and now i will try to click on purchase this item and we receive method not allowed okay so we should add this as a method that are allowed in our decorator so we already know how to do that so let's just copy one from our register page so it will be copying from here and pasting in right there okay so now if we click on purchase this item then we are totally fine and now i want to show you the results of that on the server side now you can see here that we receive the object of the form itself and there's nothing surprising with that now i want to show you a little bit nice trick that we have in class instances and that is the attribute of underscore dict like that so this takes the entire instance and displays it in a nice dictionary so it will really give you a look of what are the keys and values that are available within this purchase form instance so once i save this and i go back to our web browser and let's try to click again on purchase item to really launch the sprint line and now i can go back to our terminal and we could see down here that we got some more information now if we search for the key of submit then you can see that we actually see the submit field as an object itself now this means that we have an available key within this instance so we could access it with a square brackets so we could go to here and we could delete this from here like that and we could say submit like a dictionary okay so it is fine to run such a code and now let's see the results of that again so i'm going to go and click on purchase this item and i'm going to go back to here and now you can see that this is actually translated to an html code so this means that we can pretty much implement the same html code hard coded inside our form and then this way we will have our custom form that is also going to be accessible within the route itself now let's see what i mean by that okay so let me grab this code snippet from here and go back to our items underscore models and right before the submit form in here i'm going to paste this in and customize this a little bit now you could remember that this ginger syntax is actually responsible to this ginger syntax because this is what we saw so i'm going to change this to being in id of purchased item and i'm also going to change this name to purchased item and then i'm going to change the type to hidden now when i do this hidden this means that this input is not going to be displayed within the form basically this is just a background information that we are going to consume in the back end of our application meaning in the route of market itself so this is why i put in here hidden now the value for that is going to be the item dot name and the reason i am doing this it is because the second that i click on purchase item i want to know which item the user tried to purchase so then we can continue on taking the action that we need to assign this item to that user so once we have done this then we can go back to our routes dot py and we can take some different actions in here now i'm going to change this code from here to something else and let's try to see what happen if we try to write in here purchased item now the reason i may think that this is going to work it is basically because in the submit field we were able to access it by the square brackets and type in submit as a string so if we create a field with the name of purchase item then why it won't be accessible so let's see the results of that now if i actually go to our website and try to click on purchase this item then we will end up with receiving key error now the reason for this it is because this purchase item is not going to be accessible within the form itself beside it is going to be accessible from an entire different area now as we know already there are a lot of request types that we create to actually manage this website so flask library gives us access to that built-in request object to really have a fully control of how the request object looks like every time that we create some requests like get or post so in that case we try to create a post request and then this means that the information about the purchased item is going to be available within the built-in request object so let's go ahead and import that okay i'm going to go to python and i'm going to go to that second line where from flask is and i'm going to import the built-in object that is request like that so now that i have done this basically i can allow myself to go down here and change this code to something like the following so it will be request dot form now the reason that i have this form attribute it is because the built-in request object already includes a lot of information about all the forms that are built in in the request itself so here i could say something like dot get and here i could access the value of the purchased item so now that i have done this then let's test the results of that okay so i'm going to save that file and i'm going to verify that our website is up and running and i'm going to try to go back to homepage and then go back to get started which is the market page and let's try to purchase the iphone 10 so i'm going to click on purchase item and once i have done that then you can see that we see the output of iphone 10 so that means that we have now fully controlled and we are aware which item our user tried to purchase so now we can continue on taking more actions from here alright so if you remember i said that we are going to fix the always being shown output about the form resubmission thing so if we actually go to here and we try to refresh this page then we always will end up with receiving this message from javascript that says us that you are in the middle of form submission so to avoid this we actually have to get rid of the conditional form.validate on submit because the reason this pop-up shows here it is because every time that we go inside this route then it tries to submit some form that executes and the reason is because we don't differentiate between get request to post request but now that we have fully control of the request object we can differentiate between those request types so let's go ahead and do that okay so i'm going to cancel this and i'm going to go to pycharm actually i'm going to cut this code snippet from here so we can copy this back later on and i'm going to delete this entire conditional and now we can change this to something like the following which is going to be look like if request dot method equals to post like that so this is pretty much equal to form.validate on submit but again this is going to avoid displaying the output that we saw about form resubmission so now i can basically go with something like purchased underscore item equals to and i'm going to paste back in the code that i cut previously so it is going to be equal to request.form dot get purchased item like that and once we have done this then we can continue on and we can try to filter the item object based on the value of purchased item so we could say let's actually write this in a shortened version so i will say p underscore item underscore object like that and we could make this to be equal to item dot query dot filter underscore by and we'd like to filter by its name so it will be name equals to purchased item like that now if you remember i know it is been a long time ago since we applied this but to actually inspect into the object of the item we have to execute this dot first method so we will really have fully access to the purchased item object now okay so now that we have done this it is a great idea to verify that this object is not none before we continue on and before we continue and take some more actions so i'm going to say if p item object and then enter this conditional and now once we have this p item object we'd like to assign an ownership to the user that is currently logged in now we did not see this before but we have a built-in object that is always going to refer to the current logged in user object so the way that we can import this is going to be as easy as going up top here and import from flask login the current user built in object so make sure to do that like i did as well and now i could basically access each user field like we have in our user modules okay so now we should remember how we can assign an ownership to a specific user so let's go ahead and remember that now i'm going to go inside my modules dot py and i'm going to show you the item module which is right here and if you remember for each item object we have the option to assign an owner feel to it so in that stage we can assign the owner field to the item object that we have filtered out by using the filter underscore by function just a minute ago so we could basically go back to here and say p underscore item underscore object dot owner equals to and then i can basically refer to that current user object that we have imported and now to assign the ownership successfully i have to put in the id of the current user so it will be dot id like that and if you're confused by that line it is mainly because in modules.py we gave the foreign key of user.id so our database expects for the id of the user that we are going to give the ownership to it so i'm going to go back to our routes dot py and in that stage it is not enough to leave it as it is because in real life when you purchase some item it makes great sense to decrease the amount of the budget of the current user so the way that we can do that is by easily decreasing the budget of the user by basically subtracting the current budget by the items price itself so it will be something like the following so i can say current underscore user dot budget minus equals to the p underscore item object and then we could basically say dot price like that and once we have done such a change we need to execute that db.session dot commit line to really perform a save operation towards our database and this should be pretty much enough to really writing the algorithm of how a user can purchase some item okay so let's test this out so i'm going to go to our website and i'm going to refresh to home page and before that let's make sure that our website is up and running great so now i can go to our website and we can try to purchase the iphone 10 now the next thing that i expect to happen is to really see again the market page but now i should see the budget of 2 200 so if i click on purchase this item and let's actually see the result okay so we see that two hundred dollars and this is perfect now i know that there are a lot of steps that we have to complete here and first of them is to actually remove now this iphone 10 from here now the way that we can do this is displaying the items that their owner is none only so let's see what i mean by that so i'm going to go to our pycharm and let's zoom out a little bit so we can see what is going on here and i'm talking about the line that is responsible to send as context to our market.html so if you pay attention right here in the item query dot all here is our mistake now we'd like to filter those items by owner equals to none because it makes sense to display those items in available items section only if they don't have an owner so this is why we should change this line to something like item dot query dot filter underscore by and we should filter by owner equals to none all right so now that we have changed this in the next reload we should expect to not see the item that i purchased so if you remember i purchased actually the iphone 10 and now if i actually refresh this page we again see that resubmission output but don't worry we said that we want to totally differentiate between get to post request and we did not write in a conditional that is looking like equals to get so this is why we still see this message so don't worry about that and let's actually go back to home and then we could go to market now you can see that we only have one item that is available on market now one more thing that we'd like to implement here is to basically display a message that we purchased some item so we could flash a success message or something like that so let's go ahead and fix this so once we commit our changes we could say flash and we could raise a message like congratulations you purchased and now we could refer to the variable of the item name by changing this to formatted string and we could say p item object dot name you purchased item object.name for and we could specify the price of the item itself so we could say p item object again and we could refer to that price attribute so this should be great to really flash the message itself now i said that we should fix the resubmission output that we see always so let's go ahead and fix that and the way that we can fix this is as easy as going down here and to conditional this up like if request dot method equals to get and then we could basically execute those lines only if the request type is get and this should be enough to really not see that confirm resubmission output that we see always so if we want to verify that then we could now refresh the page and you can see that now it is totally fine and it works correctly and we don't see that from resubmission output okay so now we are going to continue on to adding some more security layers in here and now think about it if i am going to click ahead to that purchase this item then it will probably end up purchasing it because we don't have any logic implemented that says if the budget is actually not greater than the item object price then raise an error we don't have a logic like that so this is why we should write some logic to prevent from our users to have the ability to purchase an item that their budget is not enough for it so this is why we should write some more python code so i'm going to go here and now we could basically imagine a code that is going to say something like if current user can purchase okay so executing a conditional before we actually assign the ownership could be something really great and amazing so this is why what we could do in that case is writing some function in our user model that is going to receive the item object as an argument and we could really verify that if the user's budget is not greater than the item object price itself then we should prevent from them to purchase this item so this is why i'm actually going to remain this code in here but you could guess that we don't have such a method yet but let's go ahead and create it so i'm going to go inside our modules dot py and i'm going to scroll up to our users and we could write some more functions i mean methods in here so we could say def can purchase like we wrote in the routes dot py and i'm going to receive as an argument item object so it will be item underscore obj something like that and we could basically return self dot budget greater or equal than item object dot price so by doing this i am returning a boolean value that is basically going to return true or false and this step is going to really verify that the user could purchase this item so once we have this in here then it is a great idea to go to our routes dot p y and this now needs an argument so the argument is for sure going to be the p item object like that and this should be enough to really verify that our users could purchase this item so now if we don't hit this conditional then it quite makes sense to go here in else statement and raise one more flash message that is going to say let's actually scroll up a bit before we write this message and we could basically say unfold through nately you don't have enough money to purchase and let's actually refer to the object itself in here and we should change this to formatted string and now we could say p item object dot name like that and now we should add some categories to both of these flash messages so here we should say category equals to danger and up top it is obvious that we should say category equals to success like that okay so now that we have completed this there's one more step that we have to complete before we really test this out now pay attention to the following code that we have in app.route so we have request method equals to post and we execute some lines of code and we have request method equals to get and we execute some lines of code but if you pay attention we don't send our users to anywhere right after the post request completes so this is why we should decide where we want to send our users once the entire conditional of if request dot method equals to post finishes so it totally makes sense to grab the indentation in here and redirect our users back to this exact route so the user could really continue on purchasing some items so i'm going to say here return redirect and i'm going to launch the url underscore for built-in function and i'm going to write here market underscore page okay so this really should be enough to test the entire flow so i'm going to verify that our website is up and running and it is and now i can refresh our website and now we should expect for a red colored message if we try to purchase the laptop because we only have 200 left so if we click on purchase item then you can see that we receive this output that says unfortunately you don't have enough money to purchase laptop we could add an explanation mark two here to really make it nicer but the point is it works and this looks great and we actually completed the entire process of how we can assign an item to a user that is logged in okay so one more thing that i'd like to do before we close out this topic is to moving those three lines of code into being a method inside our item model so if you imagine a situation it could have been a lot nicer if we don't have those three lines of code and besides that we could have a code that is going to look like p item object dot assign ownership something like that or basically this could also be dot by okay so anything that you like will do so let's go ahead and do this okay so i'm going to undo here several times to really not ruin things out in here and we are going to create an additional method inside our items model and this will be responsible to turn the entire flow of this items route to a lot nicer so i am going to go to our modules.py and i am going to create a method this time in the item module itself because now we should assign an ownership to a specific user so it is going to be something like the following so we could say def by and we could receive a parameter that we will name it user and the lines of code that i'm going to be executed in here is pretty much going to be the same as in routes.py besides we are going to change the p item object to self so i'm going to cut this out from here and i'm going to paste this in under by and every place that we see p item object is going to be changed to self so for that and for that we should change to self and for the user we should replace those with the user that we are going to fill in as an argument so now that we have this method which we name it by we could basically execute it by only going here and say p underscore item object dot by and we only have to pass in the current user object so it will be just typing in here current user and we pretty much done with the entire process okay so now to actually test this out we have to create a new user because it will save us some time because the jsc 6 user is having currently 200 and we'd like to test this with a new user that is going to have as default 1 000 so we could log out for a minute and you can see that we see this informative message which is perfect and we could register with a new user so i think this will be jc8 that time and we could put in some valid information and we called create the account okay so we are inside the market page and now we only want to test if this change and moving the code to model.py is going to work for us so i'm going to click on purchase item and now you can see that we see this message that we see you purchase laptop for 1 000 and i see that we forgot the dollar sign in here and now you can see that we don't have any items remaining in this available items on the market section so this is perfect and the budget is updated as well to zero dollars so really the entire flow is starting to work and this is perfect only i will just change this message to being with a dollar sign and this is going to be as easy as adding it in here and this is now perfect all right everyone so i'm currently logged in with the latest user that we have created which its name is jsc8 and if you remember with this user we purchased an item that its price was one thousand dollars and this is why our budget is zero over here now to really show you how we should display the owned items for a specific user i am showing you our page because i imagine that we could basically create some bootstrap cards and by saying cards i mean like a nice looking square shapes where we will display the old items that the user has and each of those cards will include some buttons that says sell this item so let's go ahead and start working on this but first of first we should be able to query all the items that the current user owns so this is why i will go to my pycharm and i will start by going to routes dot p y and if you remember we have this built-in object that says current user and it knows how to identify the object of the user that is currently logged in so we could write a query that basically filters out the items that the current user owns so let's go ahead and do this right under our market page route but it totally makes sense to write such a filtration under the if request dot method equals to get conditional so i will go here and i will say something like owned underscore items equals to item dot query dot filter underscore by and as the expression in here i will say owner equals to username dot id i mean current user dot id okay so the reason i'm doing id because if you remember from the db relationship that we created we mark the relation between item and the user by its identifying number so this is why i can allow myself to filter this out by current user dot id and this should be enough to bring all the items that the current user owns them so now i will pass this as a context by saying owned underscore items equals to owned items like that okay so this really should be enough to go now to our market.html and start working on the implementation of how we want to display this okay so if you remember we have this call dash 8 which displays available items on the market and right here we have div class 4 which is basically designed for displaying the items that the current user owns them now in here i can write some nice html code to really start working on the way that i want to design this so we can say div class equals to row and you will see in a second why i'm creating one more row under this column and i can now start writing the iteration that we'd like to do probably so we could say for owned item in own underscore items and we could close our expression like that and right here i will say div class equals to call dash md-6 okay so i will stop here and really explain why i did what i did okay so by purpose we want to declare this as 6 because if you remember from the previous session that we created div class equals to row div element we implemented the reading system of bootstrap and the maximum size that you can locate an html element within a row is only 12. so this is why if i create six and there is more than two items then each two items it has to force itself to jump down a row and it looks nice if you display only two cards in a single row so this is why i implemented this in that way okay so right between those div tags i'd like to paste some html code that will be responsible to create those bootstrap cards that i talked about now you can find the code that i'm going to paste it in in my official website so just navigate to the episode 16 of this entire tutorial okay so i will paste this in in here and explain what is going on here as well so we have one more div tag that says card text center and bg dark so nothing really complex in here and right after it we have the card body class and right after this we have some class to display car title so we could imagine that this code is responsible to display probably in the up top of the card and the button is basically made for the option to sell the item that the current user owns and you can see the data toggle and data target as well and you should be familiar with this if you watch the last episode and here we have some paragraph that says additional text so we could edit this by displaying some more text about this item okay so if i save this file and go back to our website and refresh that out then you can see what the code that we wrote is responsible for and you can see that this is a really nice card that displays the item that the user owns now you can see that there are a lot of placeholders that we have to change them so the way that we can change them is easily by going here and edit the text that we should edit them okay so in the card title we probably want to display the item's name so it will be by accessing the variable block of jinja and we could say owned item and this is actually accessible because of this for loop and we could refer to the attribute of name of this item and by doing this this will be responsible to display laptop besides the placeholder that we saw previously and we could leave the cell this item because this is the actual purpose of the button and in the additional text we could basically give a nice informative sentence that says something like the following so this could be this item costs and then we could refer to the price attribute so it will be owned item dot price and we could add a dollar sign right here and by doing this you can already guess that this is going to display the following line so now things are looking a lot cleaner and you can already see that if there is going to be more than two items in here so this card would be located in here and then the third card will have to force itself to locate in here so this is why i went with the following approach okay so from now each step that i will be configuring will be basically the same as we did for purchasing an item so if you remember in the last episode we also created in forms.py a form for cell item form as well so this is why i'd like to create an instance of that and send it as a context to the route.py as well so it will be by going here and say selling form equals to cell item form and this is probably not up top here as the import line so we could say sell item form like that and this selling form should be sent as context to the market.html as well so down here we could send this like selling underscore form equals to selling underscore form like that now if you remember when we implemented the purchasing item we search for request.form dot get purchased underscore item because this was a reference to an input that its name was purchased item so we will go back to this route dot py to really write python code to perform action like for selling the item itself okay so this should be enough for now in the routes.py and now let's go ahead to our market.html and create a model for selling an item like we did for purchasing so i will open our market.html and i will also show you a kind reminder that in order to display a purchasing item modal we created this items underscore models html page now to really have a nice separation between selling and purchasing i'd like to create one more html file that we called name it something like owned items models like that and we could delete the auto generated html and like i said because the logic implementation is going to be quite the same i can allow myself to grab the exact same model from the purchasing item model and later on we could change some of the identifier strings or html text to make it dedicated for selling an item okay so i will go to items underscore models and i will copy the entire code under the purchase confirm and i will paste this in here and if you remember we had some special style for this model as well so i will grab the style tags and paste this in as a first line okay so now this is some dirty job but we have to do it okay so let's go over the areas that we have to change from purchasing to selling or sell or something in that kind okay so you could already notice that we have an identifier that says model purchase confirms so we could change this to selling confirm like that and we can also change the comment in here to make it nicer and if i scroll down a bit then i think it is okay to leave the item name like that and now in here you can see that there is a reference to an hidden tag that comes from purchase form and if you remember we also initialized the selling form as well so we could change this to that and now here we have a sentence that says are sure you want to buy so we can say change this to sell and in here we could say by clicking sell you will put this item back on market like that now you can already see the input inside this model as well and you can see that it has an identifier that says purchased item so it totally makes sense to change this to sold item okay so we created this in past tense so we will leave it as it is and this will be sold item as well and we'd like to keep this in hidden and the value as the same so again we have this purchase form here and this has to be selling form and besides doing this success we'd like to do is danger to really differentiate between the different actions so one will be green and the ceiling will be red okay so the close button that is here we could leave it as it is and that will be pretty much it now if you remember to trigger a model we have to trigger this identifier in here so i will allow myself to copy this statement and to really start working on two separated windows to not confuse us so we could really understand the further changes that we make from this point so i will split our panes and this will be by window editor tabs and we like to do this split vertically and in the left pane we will keep the owned items models and in the right pane we will open the not the items model excuse me we will open market.html okay so from here we are good to go and let's scroll down a bit in here and you can see that we have under call for some more things that we'd like to change in here so we have this button right and this button is actually what responsible to trigger sell this item model and if you paid attention we have here a data target that says your data target now this should be changed to something that is related with the owned item variable to really have a unique model per item so this is why i will make the owned items modal a little bit bigger and i will change this to owned underscore [Music] item like that and we should probably change all of those for all the places that we see item to owned item so i will do that just in a minute and that will be in here and as well as in here and also in here and let's catch up if we have more of that so to really make our lives easier in here we could basically search for item and we could pay attention that every item is with owned item right now so we are good to go from here and now i can really copy this identifier string and copy that out and now i will make the market.html bigger and we could paste this in right in here like that and this should be pretty much enough to really see the model itself when we want to sell an item so now i can go to our website and we could refresh it and if we click on sell this item nothing happens and this really means that we probably forgot something important and this is why i will focus for a minute in what is going on in market.html and have a look in here so in here we start our iteration and yeah we i think it is because we did not trigger this include line so if you remember to really trigger the model itself it should be recognized as an html code in the exact same page so this is why in each iteration we have to use this include in order to really have the model implemented inside the for loop so each item will trigger a separated model regarding the information inside of it so this is why i could go with something like this we could grab the code from here and we could paste this in right under the for loop and we should change this to owned underscore like that because we want to import the models html that we have just now created now i want to have a look in owned items models to really ensure that we don't have any leftovers with the owned underscore item because we iterate over a different variable name so here we are good and here we go as well and as well as in here and if we take a look in the input okay here we should also change this to own underscore item as well so i have a really nice trick that you can do for such a scenario where you want to make sure that you replace all the variables with something so you can basically use the control f and search for a specific text in your entire page now if i search for double curly brackets and item then you can see that we are good to go and nothing really exists with this expression so we could now go to our page and refresh it out and test if this works and you can see that the result is quite great now we see the title in here and we see this sentence and this button currently will not do anything because we did not configure the functionality of this button so let's go ahead and do that okay so in the left pane we have our route dot py and in the right pane we will work on some html code to display some differences now if you remember the way that we grab the item that was attempted for purchasing in the previous sessions was by going to here and say request dot form dot get and then we use the name of the input itself so this really came from this name attribute of this specific input now if we take a look in owned on underscore items dot model so i will put it in here then we have an input with a name sold underscore item so basically what we could do in route dot py we could really implement the same logic for selling the item like we did in purchasing it so i will close those and start working on the way that this should be implemented okay so we could go after the if expression in here and start working on the area what happens if the user wants to sell the item so to really differentiate between those i'd like to add a comment here that says purchase item logic and down here we could say cell item logic like that okay so we can say here sold underscore item equals to request dot form dot get and right here we could say sold underscore item now pay attention how i am keeping the same logic like in purchase okay so once we have this sold item then we probably want to grab the object of the item itself because in here we only try to get the items value itself so we could say s underscore item underscore object equals to item dot query dot filter underscore by and we could say name equals to sold underscore item and we could hit the dot first method in here now like in previous sessions if this item object is going to be not null then we can really start working on assigning this item to no one so we could go ahead and say if s underscore item underscore object and hit the column sign and enter this conditional all right so now we probably want to look to execute some method that will ensure that the logged in user is really have an ownership on this item so the way that we can do this is by creating a method in the user module we could name it can underscore cell and the can underscore cell will return a boolean variable true or false that will basically explain if the user has this item for real so this will be by saying something like if current user that can underscore cell and we call pass the item object in here now i know that we don't have this method but this is just in theory so we can really understand the idea of how i'm going to implement this now again you could pay attention how this is quite equal to what we did for purchasing the item itself so if you remember if we press here control b then this can purchase returns a boolean variable that basically ensures that the user can purchase this item so by creating a method that will say def can sell and this will receive the item object one more time like that we could really verify in here that the user really owns this item and the way that we can do this is by the following expression now if you remember up top here we have these items which is basically responsible to be a reference for all the items that this user owns so we could say return item underscore object in self dot items and this should be really enough to return us true or false because if this item object is in self dot items then it means that the user really owns this item and he can sell it so we could go back to here and if we hit this conditional again this is going to be the same approach like we did in item purchasing so here we called execute again in theory something like s item object dot cell and we again like to pass in here the current user object for this method and this cell should do the exact opposite action from the buy method so if we inspect inside buy then you could see that first or first we assigned a new owner and then we decrease the budget and then we executed the tb.session.comit so the exact opposite of this method would be def cell and we could receive the user object as a parameter and we could say self dot owner equals to none so this is the exact opposite action of assigning an ownership we assign the ownership to nobody so we could say here again user dot budget and you could already guess what i'm going to do here this time beside minus equals this will be plus equals because we want to give the money back and this will be again for sure self.price and again we can say here db.session.com it like that okay so as we have done that we can continue on the logic implementation so i can go back to our routes dot py and after we perform this action we could grab the flash from the conditional of purchasing and paste this in here and we could change this a little bit so we could say congratulations you sold s item object dot name back to market and i think this should be enough okay back to market and we could add an explanation mark and we could delete this and we forgot to close the double quotes in here and so this should be enough and we will leave the category success as it is okay so let's scroll left in here and go down now if the user could not sell this item then we probably want to raise a flash message that something went wrong and the user does not really own this item so we could say else and we could grab this from here and paste this in and we called say in general something went wrong with selling and we could refer to s item object dot name and we could leave the category equals to danger as it is all right so i think we are ready to test this out now i hope that the actions that we have taken in the last minutes made a lot of sense for you because the selling implementation is pretty much the same like purchasing it so this is why you saw a lot of copying and pasting stuff so i hope that you understood everything pretty much clear because from this point if the selling item works properly then it means that we finished everything with this website so let's go ahead and see if this works great so i will refresh our page and we can now click on sell this item and once i click on sell this item then you can see that everything is pretty much working and we see congratulations you sold laptop back to market and you can see that we have a new one thousand dollars and you can also see that the available items on the market is really updated with the information that it's supposed to so this really means that the selling logic implementation is working perfect as well alright everyone so i think this will close out our episode and like i said in the beginning the feedback of how this series was for you is really important for me so i can really know what i should improve in the next series that i will be creating in the future and i will be creating one more episode that will basically explain in general how you can deploy a flask application to production but this is not going to be specifically for this website basically i will be creating a general video that will help everybody with their flask projects how they can deploy it on production alright so if you like this video please hit the like button and also consider subscribing to my channel if you already did not and i will see you very soon
Info
Channel: freeCodeCamp.org
Views: 263,452
Rating: 4.959662 out of 5
Keywords:
Id: Qr4QMBUPxWo
Channel Id: undefined
Length: 381min 3sec (22863 seconds)
Published: Wed Mar 10 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.