Django Forms Tutorial For Beginners - Get Started Fast! (2018)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
here you all I hope your day's going great in this Jiang of forms tutorial for beginners you learn how to use Jenga forms from the ground up by the end of this video you will know how to submit data with forms what model forms are and how to use them what bound and unbound forms are how to use Django Krispies forms to make working with forms easier how to make your forms look better how to create a custom multi-value field and really everything you need to know to get started with jenga forms first off I want to clear up the confusion about what jenga forms are used for remember that they solely live on the back end however you can use them for things like generating form HTML to render on the front end or validating incoming data a form is just a class which contains certain fields every field has a widget associated with it that is used to tell Python which HTML tag it should use for this particular field when generating the HTML for us that we can display on the client side basically jenga forms make our lives easier by taking care of common tasks so I would say less time reading and see it in action we want to start out by creating a new project use Django admin and start project and I'll be naming it Django underscore forms then we can change the directory and simply use add some Mentos now you want to create a new app called my app so I manage up I start app my app and we can now use manage top I run server ok and now we can go into atom and first of all we want to head over to the settings file and simply register the new app ok and now we want to start configuring our URLs a bit to lead us to a view where we can finally start experimenting with forms I hate this comment so just remove it and then we can create a path as soon as the user hits T and next right we want to first of all include the my app the URLs and we of course have to import include as well and we can now simply control see this entire file and go to the my app and control V so simply just copy it over and as soon as we're here we want to have a path for the index as well so if nothing changes we want to use it to be led two views don't contact and now we can go into the abuse of Pi file and create a new contact view and this will for now return an HTTP response contact view let's just make sure to import it from Django HTTP import HTTP response hopefully everything works out now I want to name my apt or URLs okay what's going on I guess we have to restart a server and of course make sure to import views from the import use okay that's now working and we can simply make the migrations okay and now we want to start by making our first form and this will be a very simple contact form which we are just going to use to capture some values as soon as the user of our application wants to contact us and we want to go into the my app and create a new file called form stop PI and in here from Jango you want to import forms first of all and then we can go down and create a form the class contact form this has a subclass from forms form and similar to models we can now specify a variety of fields such as the name and we're going to set this to form store char field then the email will be set to form store email field and I want to specify a human friendly version of this label which is just going to be e-mail with this little - and then we want the user to select a category for which type of requests are sending to us so we can say categorical to form store choice field and the choices is an array of tuples and first of all first choice question and the other choices other okay of course make sure to extend that if you want to and then we want to select a subject also char field and we'll make that a required support defaults and the last we want to actually capture the message inside of a body form stop char field and now we can specify a widget and wedges are useful the actual HTML representation of a field and the widget ends case going to be form store text area and for the other two chart fields by default it's going to be a input and this case wanted to be a text area for more space okay and then let's go to the view stop i from the forms we want to now import our contact form and we now want to return a random one with the requests and the temple we want to render is going to be located under formed or HTML and then we want to pass a form which of course want to create first form will be equal to contact form just an empty form with nothing special to it and now we want to create a new folder called templates where are formed or HTML contribute sitting so create that as well and because I'm using atom with Emmet I can just simply hit this exclamation mark and then tap to old generate some HTML for me and inside of the body we can now spit out our form within normal Django templating syntax and let's see what this gives us now what happened here okay name choice is not defined let's go back to the forms and we had choice is equal to whatever we are typing in here and you can see that I'm now on my local host and what we get is a form that's not looking too good but we're going to change that as well throughout the video and you can see we have the name then the email category is this choices select field then we can provide a subject and body but of course we don't have anything to submit it yet so that's for up to us to create because as you can see if we now right-click and inspect you see that we don't get a phone tag by default so that's what we have to provide manually and we can just simply create a form the action will be post and inside of that is going to be split out Jenga foam and then we of course also want to use these years I have token and at the very end of it we want to have a new button with the type of submit and this just says submit okay that's working and now that we have that we can take care of submitting the data so whenever we are inside of here of course up until now we simply just created an empty form and forms are divided into two categories one of which is an unbound form this one because it doesn't have any data associated with it and the other type of form is a bound form which we can use to get the data out of it because we have passed at some data already and now we have to check whether the request or method is equal to post and if that is the case we want to set our form equal to contact form and instead of leaving an empty one to positive requests dub post and this will populate our contact form with whatever the user try to submit and because we know that we can never trust user input we have a specific method called is valid and that's what we can call as well so if home door is valid then we can capture all of the fields we want to so we can set the name equal to formed or cleaned data that's what you normally used to get it data in a clean format and then the name is going to be named and then we can do the same with the email for clean data email and we'll leave it at that for now because the same with the other fields so we can just try to print name comma email okay and in a form make sure to change this to method instead of action and now we can fill out all of our details Jack and then email eight AFV I'll come and subject I'll need to be provided and then buddy and now click Submit and back inside of our terminal we can see Jack and yet be calm and at this point we can of course use it to send an email or do whatever with it save it to the database I don't know and next up we will cover a concept called model forms and it's quite useful because we can simply call a method which automatically takes care of saving the model to the database for us instead of doing it manually and to demonstrate this we are going to head over to the monster pie file and create a class called snippet weights up classes from model stock model and this is only going to have a name that's HR fields with the max length of 100 and then a body that's going to be a text field and then we want to go to a string method just to represent it in a nicer way okay and then we can go to a terminal and make immigrations again and migrate ok and because it's such a common workflow to generate forms out of models that's why django wanted to provide a model form to us and i'll demonstrate how this works real quick so we can go into the forms of pi again and create a class called snippet form and instead of subclassing from forms or form you can surplus from home store model form and this is going to have a class matter where we have to first of all provide which one we want to use sa model for our model form and in this case it's going to be a snippet model and then we can specify all the fields and we currently only have name and body and of course make sure to input this number as well from the models input snippet and now we can go back into our booster PI and create in your view or snippet and it's called detail and just make sure to copy all of this basically will save us a lot of time and just substitute this one with snippet form and we can get rid of all of this because we don't need it and this one just be substitute as well and before we get into saving it we want to first of all print valid just to see that this is working and we want to of course input it as well and then we can create a new path and I'll be making this two snippet now go back into your browser and go to slash snippet and you see a completely new form of course with our same template and we can specify the name as snippet 1 anybody else I don't know ok and you see valid of course because everything works fine but still we haven't really made a new model out of it and to see this in a nicer way we can register Imola in the app in the PI so just use append or site register snip it and then at the very top we can from the models input is never and to be able to access our app in view we of course have to create a super user as well and we do this via the manager project create super user command just specify a password great and then run it again and now we can open a new tab and go to the admin route and the user name should be whatever we use and then just a password and we see a snippet raheem and if we didn't use small forms of course we would need to get all of the values out of the form that way and then create a new instance fully snippet like we normally deal with snippet the object start create but in this case we can simply and look at this cool forms of safe and it's all done for us awesome so let's check this out in action and the name is going to be Z K and the body will be whatever and just hit submit but if we now go into the admin you can see that we have a new snippet without us needing to do any other work and next up what really bugs me is that this is looking so ugly you know all of the fields are aligned horizontally and that's not what we want and to resolve this issue we can use a package called Django crispy forms which makes this a piece of cake for us and we can install this package by a pip pip install tango crispy forms and as soon as that is done we can we run a server again and now go into the settings of pi and we have to include it in installed apps as crispy install forms and the most basic thing we can perform with tango crispy forms is go into our actual template and at the top we can first of all load press be underscore forms tax and then we can use the crispy Tekin our form and after we reel that page you can see that they are already aligned a bit nicer but still not what we want and because of this we can now go into our form store pi and over at the constructor of our contact form with the init method and if you haven't yet watched my Python pee class I'll leave a link to it down in description if you want to check it out I think it makes understanding this a bit easier and instead of this we can access the superclass which is the form and then call D in it with our arguments and keyword arguments and what krispies forms provides to us is a so called form helper which we can use to specify a variety of attributes inside of our form and whatever we provide then can be used by Python to generate the HTML markup for us and that will of course save us from doing a lot of work and first of all we need to set the self door helper equal to form helper which is a class provided by crispy forms that we can first of all input from crispy crispy forms don't help her and then we also want to import from crispy form salt layout there are two classes called layout and submit which we are both going to use and after the helper we can specify self talk helper dot form method which we can set to post because of course the data should be posted to our back-end so we can do whatever with it and if we were to save this I'm just going to show you we can just go into our form to HTML and just get rid of all of this and instead of printing it out like we normally do we can use the crispy tag like this and then whatever form we pass to this simply called form and then we can also positi help him which has formed or helper I headed over to get bootstrap to come and picked up the link for the CDN and now we can use it to easily integrate bootstrap in our application and I'll leave the slim bit down in the description you can just copy it or go to get boots off the comment pick you up yourself however you want so just paste that right here again it's down in the description and I also want to add a bit of styling to this body just quick adding 20 pixels otherwise it's going to be touching the left edge which I don't want and now let's see how that looks so just refresh and you see that we get some nice bootstrap styles you can see that we still have no submit button and that's exactly what we can use the layout for that we can put it here and we can override the layout by setting itself to help them don't layout equal to a new layout and in here we can specify all of the fields in the order we want them to appear in our form and we want to keep the first ones you know all of these ones the same so name then email and category subject and body of course you can change the order of them however you want to and then we want to add a submit and this will have the label of submit and we can specify its CSS underscore class and set it to BTN success which is the nice bootstrap class we get and as you can see a submit button pops up like magic and we can use it normally just like we did before so name I don't know and then some email and hit submit and still we get our name and email instead of a view because of course that's the only thing we were printing out and next up I want to cover is very specific field called the multi-value field and this one you can basically imagine as one field that contains many other subfields and we want to use it for the name in this case although might not be the best use case but still it works so let's go ahead and we want to set name simply to name field create a new class called name field with surpluses from form store multi value field and first we want to provide it a constructor with arcs and keyword arguments and in here we can set all of the fields we want our multi value field to have and as I said it contains many forms subfields like these ones and the first one is going to be a form store char field and the second one as well and what we want to capture in this case is the first name and last name and at the end of that we can simply call super dope in it with all of T first of all the fields pasti arguments and keyword arguments as well and now we have to provide a function which is called compress and this one takes in the data list and as you can see we have two specific form fields and what data list does is it takes the value of each one of them and puts it into a list and that's what we are getting inside of this data list so for example if the user types and tests for the first field and none for the other field that won't we get inside of data lists what be equal to tests and none just as a comment that's what it will be equal to and what we now have to do is represent this in any specific way we want to be able to get it from the views and that could be custom to however you wanted but as we are getting the first and last name we simply want to return an S string and this one returns datalist zero and then we'll say space in between we get data lists with the nexus one and we are simply getting the string a first and last name with a space in between like we would expect from my name but as you can see we still only have one input and that's of course not we want because we want to use it to be able to pass two specific ones as we just said because we have two specific fields and that's why we also need to already widget em can just go on top of that and create a new class called name widget which suffers from form store multi widget and this also has an constructor with the attributes of none and that we call super though in it the initialize and Indian we can now specify our particular input types which we want this char fields in this case to have and of course we want them to be text inputs simply we don't need a text area or anything other fans like that just simple text inputs so use formed store text input and deed second bunch of p1 as well okay and then we also want to pass the attributes if we passed any and this one has the counterpart of what we have here which is compress which is decompress this takes and itself anti value and the value is whatever this function returns basically so instead of us passing any data so we can get it in our view we basically want to mimic what would happen if we took the data inside of the view and pass it to this how jenga should behave with whatever it gets and and decompress if we have our value then we want to return value dot split by the space character and again the data list is equal to first value and second value say comment and after this it's equal to first value and second value with a space in between oh really I think this is less confusing and in a decompress at the beginning value is equal to first hole and second value and at the end we want it to be equal to a list first value and second value again and of course this only applies if we have a value to begin with but if we don't we want to return just two empty strings like this so we also have to go to the name field and specify the widget as name widget okay so go back and reload and you see that instead of one we get now two separate input fields and before we get any further we want to go to the view so pile and just simply print out the name only so try out how this phone works as first thing we are going to use Bob and then Jackson and email is still going to be the same blah blah blah and then we can try hitting submit and we see Bob Jackson is a string so there isn't any list of two separate valves anymore we basically took this list which first has a value of Bob and second data value of Jackson and turned it into this string thanks to this method and now with this decompress what's going on we can also return let's say we were returning te and our e and we can see what happens as you can see we get automatically filled in whatever we put right here if there is no value and this is how the multi value field basically works and we can perform some more things with it for example use it for validation so we can go to the top and again from Django cool don't validators import the regex valid data and now in here we can set validators equal to a list and the first one is going to be reg ex validator and this takes a regular expression and of course if we are extracting a name we only want to be able to capture letters so a to z and okay H Z and then Plus which means at least one and then the error message if the user doesn't comply with this reg extra P enter a valid first name and then in parentheses only letters and copy the spell data over to this second one and this should say enter a valid second name and enter this one STL's close because at the end of this we would normally redirect the user to some kind of thanks page so there's no need to clean the form afterwards LS just quickly fill this out again Jackson buddy and now we should get a warning as soon as we submit it NEC ante by the first name only letters and s I already mentioned in the intro the other big big use case of forms is form validation because we can never ever trust user input they are always going to be some people who put in gibberish to try to break your system and that's why it's important to keep it safe that way and of course Django forms provide a nice way for us to do so and that's why we should use them anyway I hope you guys enjoyed this part and I know there's quite a lot of information to unpack if you didn't really understand all the object-oriented concepts which I put here you can just go back to my Opie class as I already said and just rewatch this video because it's really the gist of forms which you are going to be using over and over again because of course forms are an important part of web applications and yeah I hope you enjoyed this part if you did make sure to subscribe to my channel and leave a comment down below what else you want to see covered I hope to see you inside of the next one and Cheers
Info
Channel: The Dumbfounds
Views: 134,158
Rating: 4.8309231 out of 5
Keywords: django forms tutorial, django forms tutorial for beginners, django form validation, django form to database, django crispy forms, django model forms, django forms select, django forms, django web development, python web development, python, models, views, templates, admin, django, database
Id: 3XOS_UpJirU
Channel Id: undefined
Length: 29min 35sec (1775 seconds)
Published: Sun May 20 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.