# Python Flask Tutorial: Full-Featured Web App Part 3 - Forms and User Input

## Метаданные

- **Канал:** Corey Schafer
- **YouTube:** https://www.youtube.com/watch?v=UIJKdCIEXUQ
- **Дата:** 04.05.2018
- **Длительность:** 48:16
- **Просмотры:** 792,578

## Описание

In this Python Flask Tutorial, we will be learning how to create forms and accept user input. We will also learn how to validate that user input and notify the user if the input was invalid. Let's get started...

The code for this series can be found at:
https://github.com/CoreyMSchafer/code_snippets/tree/master/Python/Flask_Blog


✅ Support My Channel Through Patreon:
https://www.patreon.com/coreyms

✅ Become a Channel Member:
https://www.youtube.com/channel/UCCezIgC97PvUuR4_gbFUs5g/join

✅ One-Time Contribution Through PayPal:
https://goo.gl/649HFY

✅ Cryptocurrency Donations:
Bitcoin Wallet - 3MPH8oY2EAgbLVy7RBMinwcBntggi7qeG3
Ethereum Wallet - 0x151649418616068fB46C3598083817101d3bCD33
Litecoin Wallet - MPvEBY5fxGkmPQgocfJbxP6EmTo5UUXMot

✅ Corey's Public Amazon Wishlist
http://a.co/inIyro1

✅ Equipment I Use and Books I Recommend:
https://www.amazon.com/shop/coreyschafer

▶️ You Can Find Me On:
My Website - http://coreyms.com/
My Second Channel - https://www.youtube.com/c/coreymschafer
Facebook - https://www.facebook.com/CoreyMSchafer
Twitter - https://twitter.com/CoreyMSchafer
Instagram - https://www.instagram.com/coreymschafer/

#Python #Flask

## Содержание

### [0:00](https://www.youtube.com/watch?v=UIJKdCIEXUQ) <Untitled Chapter 1>

hey there how's it going everybody in this video we'll continue with our Flash series by learning how to create forms and also how to validate user input so the application that we're going to be creating is going to have the ability for users to create accounts login make posts and logout and things like that and the first part of that process is to

### [0:17](https://www.youtube.com/watch?v=UIJKdCIEXUQ&t=17s) Create a Registration Page

create a registration page where a user can create an account on the website and then be able to log in and log out and that's what we're going to be doing in this video so let's go ahead and get started now if you were to create forms from

### [0:28](https://www.youtube.com/watch?v=UIJKdCIEXUQ&t=28s) Create Forms from Scratch

scratch then that can get pretty complicated pretty fast you would have to put in different kinds of validation checks to make sure that the user was inserting information correctly you'd also have to make sure that their passwords matched and you might have to write some regular expressions to make sure that they entered a valid email and things like that but luckily this process is so common that we don't have to reinvent the wheel there are extensions out there that have already put in all the hard work so that you don't have to and the most popular extension for working with forms and flask is called WT forms and that's what

### [1:00](https://www.youtube.com/watch?v=UIJKdCIEXUQ&t=60s) Wt Forms

we're going to be using in this video so first we have to install this and we can do this with a simple pip install so I'm

### [1:06](https://www.youtube.com/watch?v=UIJKdCIEXUQ&t=66s) Pip Install

here with in my virtual environment but you could also do this without a virtual environment so I will say pip install and that is flask - WTF for WT forms so we'll run that and go through the installation and once that's installed I'm going to open up our existing project and our text editor so I'm going to open up sublime text here and now let's create a file where we can put these forms so I'm going to create another file in our project directory and I'm going to call this forms dot p/y now these forms could go directly into that application module that we've been writing but it's best to split things like this out into their own files so that everything has its own place that way if we need to update a form in the future then we know exactly where to look so it's better to have this stuff split up into smaller more manageable sections of code rather than one larger application file where everything is in one place and hard to find okay so now within this file let's create our forms so first let's import this into our application by saying from flask underscore WTF import and we want to import flask for now if you've done web development for some time and then you may be used to writing forms in HTML and this is going to be a little different using this flask extension so we will actually be writing Python classes that will be representative of our forms and then they will automatically be converted in the HTML forms within our template so let's see how to do this so let's say that we wanted to create a registration form then we can class so I'm going to come down here and say class and then we will call this registration form and this will inherit from flask form and now within our form we're going to have different

### [2:50](https://www.youtube.com/watch?v=UIJKdCIEXUQ&t=170s) Form Fields

form fields and these form fields are all going to be imported classes as well so for example let's say that the first field that we want in our form is a user name and the user name is going to be a string field and this won't be imported from the flask wdf package but instead the WT forms package and that was also installed with the PIP install so we don't need to do anything extra there so we can just say from WT forms and then we can import this string field class and now within our registration form class we can create a new attribute and we can just say username is equal to and then this will be a string field and then the first argument here is the name of this field so I'll call this user name and that is also going to be used as the label and our HTML okay so that's easy enough to create that but now also when it comes to user names there might be a few limitations that we want to put in place so first of all we want to make sure they actually put something for their username and just don't leave it empty or blank second we wouldn't want a user to be able to create a username that's you know 50 characters long because then it would look weird on our website so let's say that we want to allow user names that are between 2 and 20 characters so to put these checks and validations in place we

### [4:11](https://www.youtube.com/watch?v=UIJKdCIEXUQ&t=251s) Validators

can use something called validators and they will be another argument that we pass in to our field so let's add a list of what we want validated by coming in here and passing in another argument and this will be validators and this is going to be equal to a list of validations that we want to check and just like with the fields these validators are also going to be classes that we import so to make sure a field isn't empty we can use the data required

### [4:38](https://www.youtube.com/watch?v=UIJKdCIEXUQ&t=278s) Data Required Validator

validator so let's import that and this is going to come from WT forms dot validators and then we can import that data required validator just add that to our list of validator so I'll copy that and paste it in here and put in these parentheses and be sure that you have those parentheses after the class okay so now if we want to make sure that the username is between two and twenty characters then we can use

### [5:08](https://www.youtube.com/watch?v=UIJKdCIEXUQ&t=308s) Length Validator

the length validator so let's include that in our imports so after data required I'll come up here and also import length and now we can add this to our list of validators as well so I'll say length and then we'll actually pass in some arguments to this length so I'll say min is equal to two and Max is equal to twenty and this line is getting a little long here so we can always break this up on multiple lines if need be so now we can see that we have a list of validators here of data required I mean meaning that it can't be empty and also a length validation that gives a minimum and a max amount that a username can be and that's why using this extension is so convenient because we don't have to write these from scratch okay so moving on let's write another field now and the next field that we're going to want is an email so I can just say email is equal to and that's also going to be a string field and the label that we want for that is going to be email and let's also pass in some validators for this as well so remember this is going to be a list and we want the data required for this email as well because we don't want them to leave that empty and also we're going to want to make sure that this is a valid email address and we can do that with the email validator so we also need to import that so up here at the top we can just import email and then pass that into our list of validators as well okay and lastly for this registration form we also need fields for a password and also a password confirmation so we'll need to use a password field for those so let's import that so right after this string field let's import password field and now we can add these in so I will say password is equal to this password field and we just want the label to this to be password and we also want some validators for this as well so let's pass in validators and the only one that we want for this is going to be data required I mean you could do a minimum length on this if you want but we won't for this specific application okay and

### [7:16](https://www.youtube.com/watch?v=UIJKdCIEXUQ&t=436s) Password Confirmation

now we also want a password confirmation so it's basically going to be the same as this field here but a little bit different so I'll just call this confirm password and for the label here I'll say confirm password and we will move these validators to the next line and we just want that to be a data required validator and that's good enough well actually there is going to be one more validation on this confirm password field because we want to make sure that the password and the password confirmation are equal so we need to use the equal to validator so up here in our imports I will import equal to and then I'll add that to our list of validators for the confirm password field so I will say equal to and now the argument here is the field that we want this to be equal to so the password field so we'll save that and let make sure that I closed everything out here correctly and I did okay so that is good so once we finish these forms we now need a submit button to send that information to us and we can do that with a submit field so now we need to import that so up here at the top I will import submit field and then we can add this field to our form just by coming down here into our class and then saying submit is equal to the submit field and the label for this since this is a registration form I'll just say sign up as the label here so that is going to finish up our registration form so now let's create a

### [8:46](https://www.youtube.com/watch?v=UIJKdCIEXUQ&t=526s) Create a Login Form

login form that will be pretty similar so I will just copy our registration form here and paste it on neath and now we'll just change this

### [8:56](https://www.youtube.com/watch?v=UIJKdCIEXUQ&t=536s) Login Form

around to be a login form instead of a registration form so first I'm going to change the name of our class and I'll call this login form now first of all you can choose to either login with the username or the email it's up to you I like logins that use email instead of usernames because it's easy to forget a username and it's less easy to forget your email so I'm gonna use the email as the login form there and all of those validators for our email are going to remain the same they will also need to login with a password and all everything for that field will be the same we no longer need a confirm password because they did that when they registered and

### [9:36](https://www.youtube.com/watch?v=UIJKdCIEXUQ&t=576s) Add a Remember Field

I'm also going to add a remember field to our login form and this will allow users to stay logged in for some time after their browser closes using a secure cookie so I'm going to put in a field here called remember and this is going to be a boolean field so let's come back up here to our imports on these fields and we're going to import boolean field which basically is a true or false so we can paste this in down here and we just want the label for this to be remember me now we need a submit button for this form as well but instead of sign up we want this label to be login okay so that is going to do it for those two forms for now when we use these forms we need to set a secret key

### [10:22](https://www.youtube.com/watch?v=UIJKdCIEXUQ&t=622s) Set a Secret Key

for our application a secret key will protect against modifying cookies and cross-site request forgery attacks and things like that it's simple to do we just need to go to the top of our application file here and right under our app variable we can set a secret key by saying app dot config and that is how you set config values on our application and this is going to be the secret key and we will set this equal to an empty string for now and ideally you want the secret key for your application to just be some random characters now a good way to get some a good set of random

### [11:02](https://www.youtube.com/watch?v=UIJKdCIEXUQ&t=662s) Random Characters

characters in Python is to pull up your command line and start the

### [11:07](https://www.youtube.com/watch?v=UIJKdCIEXUQ&t=667s) Python Interpreter

Python interpreter so I will do that now and I'm gonna use this built-in secrets module so I'm gonna say import secrets and to get a big random string of characters I'm just going to use the token hex method on this so I'm gonna say secrets dot token underscore hex then we can pass in a 16 here and that's 16 there is just the number of bytes so now I have a pretty good random string here and I'm just going to use this as my secret key in this video so I'll exit out of our Python interpreter and clear the screen and then go back to our application and paste that in here and you'll likely want to make this environment variable at some point and we'll look at doing that later on in the series okay so now let's use those forms that we created here in our application so first we need to import those forms and those are in the form stop py module so and it's within the same directory as this module here so we can just import directly from that so we can say from forms import and that was the registration form make sure I spell that correctly and the login form and now

### [12:17](https://www.youtube.com/watch?v=UIJKdCIEXUQ&t=737s) Routes

let's create some routes for our registration and login so we can see how these get converted to HTML so first

### [12:23](https://www.youtube.com/watch?v=UIJKdCIEXUQ&t=743s) The Registration Route

let's create the registration route so down here above our main conditional I'm going to create another route so I'll copy one of these existing ones and I will call this route register and we need to change the function name as well and now we need to create an instance of our form that we're going to send to our application so we can say form is equal to registration form and we want to put in the parentheses there to create an instance of that and now we can pass this form to a template now we haven't created register or login templates yet but we will in just a second but I'll go ahead and pretend that they're there for now so I will say down here at the bottom return render template and we will create a template called register HTML so that's what I'll fill in there so now we can add in some additional information here so I'll pass in a title of register for that Paige and also we want to pass in our form so I would just say form is equal to form that way within that template we have access to this form instance here

### [13:33](https://www.youtube.com/watch?v=UIJKdCIEXUQ&t=813s) Login Route

and now let's do the same thing for a login route now this is going to be pretty similar so I'm just going to copy our entire register route here and then change a few things so I will change the route and the function name to login we want this to be our login form we want to render the login dot HTML template we want the title to be login and we can say form equals form because now we're going to be passing in that instance of the login form so now that we have these routes created now we just need to

### [14:04](https://www.youtube.com/watch?v=UIJKdCIEXUQ&t=844s) Create the Templates

create the templates that use these form variables that we just passed in so let's go ahead and create those templates so up here in my templates directory I am going to create two new files so I will recreate register dot HTML and I will also create new file called login dot HTML and now let's grab some code from our about page just to get us started so everything that just extends the layout and opens up that content block so I will do my register route first so I'll paste that in here so we can see that we're already extending our layout template and we learned how to do that in the last video when we looked at templates and now we

### [14:45](https://www.youtube.com/watch?v=UIJKdCIEXUQ&t=885s) Form in the Content Section

want to put our form in the content section of this page and to do this there's going to be a little bit of typing so bear with me here but I will open up a div and this div I want to give the class of content section this is a style that I have in our main CSS file that will just make this look a little nicer and now we want to open up a form tag so we'll say form and we want the method of this form to be equal to post and we want the action here we'll just set the action equal to an empty string now that means that when we post this form it's just going to go back to the same route it's going to post that information to the same route that we're currently on ok so now we're ready to

### [15:30](https://www.youtube.com/watch?v=UIJKdCIEXUQ&t=930s) Putting in some Form Fields

start putting in some form fields here now the first feel that we need is going to be one called form dot hidden underscore tag now remember when you're actually accessing variables in our template you do have to wrap it in these double curly braces here and then we are accessing the form instance that we passed in to this template and now we're using this hidden tag method here now that hidden tag is something that you need to add in but don't worry too much about what it does it's adding something called a CSRF token or a cross-site request forgery token and when I said earlier that setting our secret key for our application would protect our form against certain attacks well this hidden tag here is part of that protection so add it in but you don't need to worry about the underlying details but you definitely need it okay so now let's add in our other form fields here and I'm also going to add a couple of HTML and CSS classes here as well so I'll add a field set and we'll set a class here equal to form group and this is all bootstrap stuff just to make this look a little nicer and then we will pass in a legend so this is going to be the legend for our register form so I want this to say we'll say just join today and let's also give this some classes as well so I will give this a class of border bottom and also mb4 which is just a margin bottom with a value of 4 and now let's create

### [17:00](https://www.youtube.com/watch?v=UIJKdCIEXUQ&t=1020s) Form Groups

our form groups and those are going to be within divs so I'm going to give this a class of form group as well so form - group and within this div now this is where we're going to actually use the fields from our form that we passed in so we're going to want those double curly braces and now we can say form dot user name dot label and that will print out the label from our user name field now we also want to give this a class as well so we can do that by putting in some parentheses here and passing in a class argument so I'll say class is equal to and we want this equal to a form control - label and again this is up this should be a dash here and again this is just some bootstrap stuff to make these look nicer okay so that would actually print out the form label there but we also want the field itself so I'm going to copy this and paste it in here but instead of just the label I'm going to do form dot username and the classes that I'm going to use for that is going to be form control and also form control - LG for large okay so now that we have one of those we can just copy and paste this for the rest of these so we'll do another form group here the next form group will be the email so I will change both of those there to form email dot label and form email and we'll keep those same classes and now we want to do the password field so I will paste that div and again and instead of username we want to change this to that use that password field and leave the same classes again now we want the confirm password field so we'll paste that in again and change both of these to confirm underscore password now if you're wondering where I'm getting these field names here these are the variable names that we specified here within our class so we want all of those to be equal to these variable names here so go back to that register template so that confirm password field is the last field that we want in our field set now we still have the submit button here so I'm going to create another form field div here and I just realized that all of these are spelled wrong and I've been copying those the whole time so I'm going to go back and change that so I will highlight all of those that say dir those need to be div for div and then I'll put a closing tag in for that one there and now we want to

### [19:39](https://www.youtube.com/watch?v=UIJKdCIEXUQ&t=1179s) Submit Button

put our submit button so within this last form group here I'll put in our double curly braces we want to say form dot submit and we also want a class for this as well so we'll say class is equal to and we want a button clasp on this BTN and also BTN outline - info and that's like bootstrap that's a nice little blueish outline button that they will style for you okay so that will do it for our form now since we're on the register page you'll see on a lot of websites they'll have on the register page it'll say you know do you already have an account well if you have an account then just go and sign in instead of creating a new account so let's put something like that here as well so we'll add in another div below our form here actually below that div that the form was wrapped in and we'll give this a class as well so we'll say class is equal to we'll give this a border of top and also a padding top of a value of three and now within here let's do a some small text and let's give this small text a class of text - muted and that just kind of fades out the text a little bit and then we'll put in the text here already have an account question mark and that will put in a link to the login page so this is going to be an anchor tag I'll give this anchor tag a class of a margin left of two just to give it some spacing from that text there and now we want an href equal to and we want this to link to our login page so remember if you want to link somewhere it's always a good idea to use the URL for function so we'll say URL underscore four and we want to pass in the link to the login page now just remember that the value that we're passing in to the URL for function is not the name of the route it's function so if I go back to our application we are actually passing in this value here not this so we want the name of the function so that's what we have there and now we need to close out this linker to anchor tag so I will give this text I'll say you know just sign in and then close out that anchor tag there okay so it's been a while since we viewed our application in the browser so let's save what we have now and see what we get so far so let me save this and now if I go back to our command line then we can run our current application by saying PI and then the name of our application so we didn't get any air so that's good so let's open up our page so that was local host on port 5000 and now let's go to that register page that we just created and see if we get that form so I'll say register and go to that form and we can see that this looks pretty good so far so we have our form legend here and then it did get all of those forms that we created in our forms file so we have our user name email password and confirm password and down here is that link where it says already have an account sign in that'll take us to our login route but we don't have anything in that template yet so it's just a blank page so let's go out and actually fill out this form so I'm going to just fill in some values here and then submit this to see what it currently does so now if I fill all that out and then click our submit button then we can see that it returns a method not allowed err and the reason that we get that is because it's submitting a post request back to the same register route with our form data but we currently don't accept post requests in that route so to accept a post request we need to add a list of allowed mess methods in our route so if I go back to sublime here and go to our flask application file up to our register route then we can add a list of allowed methods by passing in an argument of methods is equal to this is going to be a list and we want this to be equal to get so it accepts get requests and also post so it accepts post requests which is what we just made in the browser so now if I save that and go back to our browser and then reload our register page and we can fill this out again I'll just fill it out with some sample values here really fast and then hit the submit button then we can see that now we don't get that error but now it just posts the data and directs us right back to the register page so we have no idea if the form validated properly or not so before we wouldn't render our register template in our route let's put in a check in place that checks whether we have post data and that is and that data is valid for our form so to do this I'm going to go back to our application here and after we create our form but before we return our template I'm going to use this validate on submit method so I'll say if form dot validate on submit and as you can probably tell by the name this will tell us if our form validated when it was submitted so now I'm going

### [24:58](https://www.youtube.com/watch?v=UIJKdCIEXUQ&t=1498s) Flash Message

to use something called a flash message in flask is an easy way for us to send a one-time alert so first I'll have to import this and this is from flask so from flask I will import flash and then come back down here to our conditional and now we can add the message that we want to display when we've created a user successfully so I will say flash and pass in a message of and this is going to be an F string here since I'm going to pass in a variable so I'll say account created for and then we will pass in the form dot username dot data then we'll put an exclamation point after that as well now I'm using Python 3. 6 and that's why I can use this F string here I suggest that everyone used the latest version that they can but if you're still below python 3. 6 then you're gonna have to use the format method on that string to fill in that placeholder instead of this f string because the f strings are only Python 3 6 and above so if you get an error there then that's probably what it is ok so now we have a flashed message here but I want to be able to tell the difference between the different kinds of alerts so bootstrap has different alert styles for successes and warnings and errors and the flash function accepts a second argument that is called a category so I'm going to pass in the name of the bootstrap class that I want this alert to have and that is success so I'll put in a comma and pass in a second argument to this flash function here and this is going to be the string success ok and now that we've got our flashed message now let's redirect the user to a different page because you don't want to fill out a form and then just get redirected back the same form after you submit it that would be a little confusing for the user so instead we'll redirect the user to the home page so to do this we're going to need to import the redirect function

### [26:53](https://www.youtube.com/watch?v=UIJKdCIEXUQ&t=1613s) Redirect

and that is from flask so I'll come back up here to the top and after our last import I'll also import redirect then come back down here inside of our conditional so when the form validates properly we will say return redirect and we want to redirect to the URL for so we'll use that route URL for function again and if we want this to redirect to our home page and again that is the name of the function for that route so we're redirecting to here okay so this should all work except for one thing we haven't updated our template to actually show the flashed messages yet so I'm going to put this within our layout template so that flashed messages pop up on any page so I'm going to open up our layout dot HTML and let's just assume that we want to display any of our flash messages up here at the top of our content so I will come down to our block content here and now right above this content I'm going to display these messages so I'm going to open up a code block so that is a curly brace two parentheses and then the closed curly brace and let me get rid of that one there and in this code block we're going to use a with statement so I will say with messages equal to get flashed messages and this is a function that will get the flashed messages that we send to this template and we want to also pass in an argument here of with categories equal to true now that will allow us to grab this success category that we passed in to that flashed message which is the bootstrap class that we're going to use and so now I'm going to close off this block so I will put in a closed block here and say end with now within our block here we want to print out any messages if there were messages returned from this get flashed messages function so we can open up a another code block and we'll say if messages and then we'll also close off that code block as well so we'll say end if and now within here this will mean that if messages was not empty then it means that we have some flashed messages to display so now we can loop over those flashed messages so I'm going to open up another code block I know this is getting a little nested here but we can say for category comma message in those messages so since we said with categories equal true we're going to get two values from these messages so for category and message in messages and now we can end this block as well so we'll say end four and now within here we can finally print out this message so I will create a div within here and this div I'm going to give a class equal to and we want to set this equal to alert and also alert - and then the category value so if we want to put in a value we need those double curly braces and we're going to set this equal to category so for example since we passed in success this class is going to be assigned alert - success and we'll see this in action in just a second so now within this div we want to actually print out this message so I'll just pass in our message variable within our curly braces there okay so now that we have all of that in place let's make sure that it all works if our forum validates properly so let's open back up our site let's make sure that our server is still running and it's not so you might see this sometimes if you actually save your file and there's a syntax error at the time that you save it then it might shut down your development server so to run that again you can just rerun the file again so now we don't have any errors so that's good so let's go back to our site and reload our register page and load that up and now I'm going to fill out this form correctly so that it will validate so I'm going to pass in valid emails and passwords and all of that and now if I submit this valid form then we can see that we got redirected back to our home page with our flash message that an account was created for our username and in that case our username was CMS now we didn't actually create an account for that user we will need a database for that and that is what we'll be covering in the next video but now we know our forums are validating correctly and giving us some feedback now these flash messages are nice but like I said they are only a one-time alert so if I reload this homepage then we can see that flash message goes away okay so lastly let's

### [31:53](https://www.youtube.com/watch?v=UIJKdCIEXUQ&t=1913s) Validation Feedback

give some validation feedback to our end user so that if they input incorrect information then they know exactly what it is that they did wrong and what they need to fix so if I go back to our registration form and if I fill this out but I give a bad email address I'll just put in some gibberish there and do the password correct then submit that then we can see that it just sends us back to our form because our form was invalid but we have no feedback for our user as to why it was invalid so let's go back to our registration template and fix this so I open back up our editor here and open up that register template so for each field that we have here each of those fields will actually have a list of errors if that field was invalid so we can open up a conditional and print out those errors so the way that this is done in bootstrap is that you add a class of is and valid to your field and then you put a div underneath that with the class of invalid feedback and then put in the error there so let's see what this looks like so I'm going to go underneath our label here and I'm going to just keep this valid feedback form here and now let's put in one that has errors so I'm going to open up a code block here and this is going to be an if statement so I'll say if form dot username dot ere's so it's only going to hit this conditional if we have any heirs and then I can end this if block so I will put in a code block here and say end if and now within here we want our username field just like we have on the outside here but we also want to add a class of is invalid to that field and underneath that invalid field we also want to give a div with a class to invalid - feedback and now within this div we want to print out all of the errors that we have so I'll open up a another code block here

### [34:02](https://www.youtube.com/watch?v=UIJKdCIEXUQ&t=2042s) For Loop

and this is going to be a for loop so we'll say for errors in and fix that typo there so we're going to say for errors in form dot username err so I'll just copy and paste that there and then I will close out this for loop by saying in for and we will just print out a span of all of these errors so we want to print out this error and actually here I should have said for error and errors not errors so I will print out that error variable there from the for loop okay so I know that this is kind of a long section here but hopefully that all made sense so if our form had errors on it then it will print out this form field and also these errors but if we have no errors then we just want to print out what we had before so we can put this inside of the else block of this if statement so I will put in an else here and that is where we will move the valid form or the valid of field from that section so I will paste that in there now I know that this can look like a lot here just to print out the validation errors and honestly forms and validation is really where the Flast bootstrap extension has some advantages but I still like doing these myself because I like to be able to easily be able to make design decisions if I want to change the look of something and I feel like you just have more control overdoing that if you do it manually okay so now we want to put in these

### [35:36](https://www.youtube.com/watch?v=UIJKdCIEXUQ&t=2136s) Validation Errors

validation errors for all of the form or all of the field sections in our form so I'm going to copy and paste this in every section so I'm just going to overwrite the valid input for the email and also for the password confirm password now I just paste it in the username field for all those so now I'm going to change that use the multi cursor functionality within sublime text but you could use a Find and Replace functionality within your editor so within sublime text I can just highlight all of these here and change these all at once so instead of form dot username we want that to be formed email so now I'll go down here to our password group and change these user names to password and now go down here to our confirm password group highlight all those user names and change that to confirm password now if you misspelled any of this or run into any problems at this point then remember I do have all of the source code for these videos on my github and you can always copy and paste from there so that you can be sure that you didn't make any small mistakes here or there and the link for that is in the description section below okay so speaking of which let's make sure that I didn't make any small mistakes by making

### [36:57](https://www.youtube.com/watch?v=UIJKdCIEXUQ&t=2217s) Form Validation

sure that this form validation is now working so let's save that and make sure that our server is still running and it is and pull up our website and we will reload our register page and first let's just submit a form with zero information so if I just submit this form then we can see that we get the few the feedback on every single field that says that this field is required and it's those bootstrap classes that we added in that handles the coloring of the red text and the red outline on the actual field there so now if I put a user name that is too short remember if we said that a user name has to be at least two characters and also an invalid email so I'll just put in an email of Cori and also I'll put in passwords that don't match so I'll do this one and just say testing and then the when I'll put in some gibberish so now if I hit submit then we can see now that it's telling us that our field must be between 2 and 20 characters long and that we have an invalid email address and also that this field must be equal to the password and if we had multiple errors on any of these than it would show all of those as well so we're getting some good feedback here to let the user know exactly what they need to fix in order to create their account properly ok so we're almost finished up but we were also going to do our login page now this is going to be a lot faster because we've already done most of this work for the register page so let's copy our register template to our login template so I'll go back to our page here and copy this big long register template here into our blank login template and now there are some things that we need to change with this form so here at the top we will change our legend and our legend we will change to log in and remember we were logging in with our email and not our username so I'm just going to get rid of this entire form group div here that contained our username so I'll get rid of that we're going to keep the email we are password this confirmed password we no longer need so we can get rid of that form group now we did have that Remember Me field that we needed to add in but this is going to be a little different from the other fields so this is going to be a div and this is going to be a bootstrap class equal to form - check since it's going to be a checkbox and we don't need any complicated validations here because this is either going to be checked or not checked there's not really anything that you can do wrong here so now we can just put in these field values so first I'll put in the check box so we'll say form a form dot remember and we want to pass a class into this so we will say that this class is equal to form - check - input and also we want to pass in the label for this field so we'll just copy that paste it in below here so this is going to be form dot remember dot label and instead of 4 check input this is going to be form check label for the class there now also on most login pages you'll see a link for if you forgot your password then you

### [40:10](https://www.youtube.com/watch?v=UIJKdCIEXUQ&t=2410s) Password Reset

can do a password reset so let's add one of those in as well so I'll put that right after our submit button and I'll just do a small tag here and I'll give this a class of text muted just to make that a little subtle I also give it a margin left of two just to spread it away from that submit button a little bit and now we want to add in an anchor tag here now we don't have a URL for this forgot password link yet that we'll be doing later in the series so if you ever just want to do a dummy link then you can just put in a pound sign there and that will just be a link that goes nowhere so for the text for this link I'll say forgot password with a question mark and also on our register page I said that there's usually something that says you know do you already have an account well then you can sign in here also on most login pages you'll see something that says something like well do you need an account well you can register here so that's what we'll put here so we'll say need an account and instead of putting a URL for our login page we'll put in register page and this the text for this link will just say sign up now okay so now with those changes in place if we save those and pull back up our website so our server is still running if now we go to our login page then we can see that now we have our login form okay so this is looking pretty good now we don't currently have any users but let's put some temporary code in here to simulate a successful login so I'm going to go back to our application code and go down to our login route and we also want to see if this form is valid on submission as well so we'll copy this conditional here and paste this in now that means that we also need to accept post requests to this route as well so just like we did with our register let's copy this section that allows post requests to our login route and now within our conditional let's just put in some fake data here for now to simulate

### [42:24](https://www.youtube.com/watch?v=UIJKdCIEXUQ&t=2544s) Simulate a Successful Login

a successful login so I'm just going to say if form dot email dot data so that's the data that was submitted in the email form if that is equal to admin at blog. com and our form dot password dot data is equal to and we will just do a password of password which is normally a bad idea but this is just going to be temporary here until we get our database setup so if they submit our login form with an email of admin at blog comm and a password of password then we want to simulate a successful login so we'll do a flashed message like we saw before and this is just going to say you have been logged in exclamation point and remember we want to pass in a category in here that'll be the bootstrap class and that'll be a bootstrap class of success and then we can return a redirect to our home page so we'll do URL for and go to that home route and now we'll just say that any other submissions are invalid so we will put in an else statement here so anything that isn't an email of admin blog and a password then we'll say that that's an unsuccessful login so we will put in a flash message here and say login unsuccessful please check user name and password okay now instead of passing in a category of success there we really want this to be like a Red Alert and in bootstrap that class is called danger for the alert and now at this point we don't want to return anything because it will just fall down here to this render template where it renders the login page again so I will clean that up and save that okay so if we did all of that correctly then we should be able to do a fake

### [44:32](https://www.youtube.com/watch?v=UIJKdCIEXUQ&t=2672s) Fake Login

login with the email that we specified here and our fake password so let's make sure okay so we had I save that when we had a mistake in our file so if I rerun our server there now our server is running so our web shot site should be running as well I'll go back and reload our login page and let's just try to login with some incorrect credentials so I'll say test at test comm and some made-up password so if I login then we can see that we get that red danger alert that says login unsuccessful please check user name and password so now if we change this to what we specified so admin at blog comm and a password of password if we login we get redirected to our home route and it says you have been logged in okay so now one very quick thing here and then we'll be finished up with the video when I pasted in the snippet of our navigation bar into our layout template the navigation bar currently is using direct links to our different routes and this works fine sometimes but if we ever change our routes for any reason then we want our website to pick that up automatically instead of us needing to remember to change it in multiple locations and as we've seen several times now we can do this with that URL for function that we've already used a couple of times and you definitely want to utilize that function a lot because it makes linking to different pages pretty effortless so the only reason I didn't do this in the last video is because our login and register routes didn't exist yet and using URL for to a non-existent route will throw an error so let's see what this looks like to convert existing links to use that URL for function so let's go back to our project and open up our layout template so I still have that open here and now we want to go down to our navigation links so our navigation links are up here in our header so they are right here and right now you can see that these are direct links to you know ford slash about ford slash login button says let's change these to use the URL for function so I will put in those double curly braces say URL four and we want this to be the URL for home and I'll just copy this and do the same for our other routes so this will be the URL for about login and this will be the URL for register so just make sure that worked if we go back to our website and reload our homepage and we should be able to click around and see the forms that we've created and go to all of these different links with no problem okay so I think that is going to do it for this video I hope that now you have a good understanding for how we can work with forums and flask and also how we can validate the data that the user sends to our route and in the next video we'll learn how to use a database so that we can actually store this information and implement a real registration and login system so if anyone has any questions about what we covered in this video then feel free to ask in the comment section below and I'll do my best to answer those and if you enjoyed these tutorials and would like to support them then there are some ways you can do that the easiest way is to simply like the video and give it a thumbs up and also it's a huge help to share these videos with anyone who you think would find them useful and if you have the means you can contribute through patreon and there's a link to that page in a description section below be sure to subscribe for future videos and thank you all for watching

---
*Источник: https://ekstraktznaniy.ru/video/12356*