AJAXify Django Forms // Django Tutorial // Learn Python Django

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
so you know when you click that like button on Facebook it automatically registers it in the database like I click like i neva gate away from that like and go back to it I'm still liking that page yet through that whole process the actual web page never changed this is Ajax this is asynchronous JavaScript and XML that's what Ajax stands for so what that means is when I click on something instead of the page reloading like a synchronous request the page doesn't have to reload that's because there's all these things going on in the background which is being handled by JavaScript itself javascript is actually handling the request for us so our browser our page doesn't need to refresh at all and that's the purpose of using Ajax and you see it in the majority of modern web pages out there right it's out there so much that it's just really a big part of building a web application so we want to learn how to do it with Django forms and of course we actually are going to be following along with this guide courtesy or1 PSDB that guide is going to be updated as we get comments from you guys if necessary but really this is going to be your main reference on how to ajaxify your genuine forms in the simplest way possible yes there are other ways to do this but what we want to do is take a form we're going to make our own form and then we are going to add Ajax to it so initially it's not going to have Ajax initially it's literally just going to work off of a standard Django form so we can see it in action just as a standard uniform so what we're going to do is go ahead and get started now a couple things that you're going to want make sure you have done number one your time Jango installed this is definitely means that you also have some experience with Django so at least try Django our latest one which is try doing a 1.11 those two things are pretty much required to get this done hopefully you already knew that so we're actually going to also reference the that's on github so if you go to github you'll see our ajaxify Django forms code here and this is the code that we're going to be using now we're also going to have the final code on here as well I'll actually put it into another directory called final SRC so SRC this first one is the blank source that we're working with just for your own reference now what we're going to be doing is first of all creating this Django form now this form can be used as a standard form or as you know a model form it doesn't really matter so let's go ahead and just copy this code here I'm going to create form stop hi a lot of this stuff should be absolutely review for you at this point but there's a form it's got an email form in a name that's all we're going to go ahead and create a form view of course this could also work on a function based view but we're really just going to be covering the form view itself so it's got a lot of default things already built in and I have the form also in there as well so this is that drawing form from the app notice that I called it your app much like in the docs here but yeah you don't have to call it that okay so now that we've got this I'm gonna go ahead and bring it into my URLs and we'll go ahead and import it in here from your app for views import join form view I'm going to just copy this one off and we'll just call this join join form view as view and we'll put a little dollar sign here to signify the end of that URL pattern let's go ahead and run our server so python managed to py run server and we cannot import the name join form view so let's make sure we have the name correct and we have everything saved saved it now it's working we go ahead and open up my localhost here and of course my URL is routed I go ahead and go into it and I see my form actually rendered of course I already have the template created for it so that's already there of course all of that is also on our source code here in the template so if you wanted to check that out but we have our form there right very simple basic stuff so what I want to do is actually update my form to handle Ajax related things I'm gonna go ahead and copy this code for just a moment and we're going to go back into our view and paste it in here now form invalid and form valid these are methods that are inherited from the form view of course and that's where this stuff is coming through right so it's getting the response either way whatever it is and then handling the data as such now I'm going to go ahead and leave out the Ajax stuff for just a moment so we can see the data that may or may not be coming through I'll just go ahead and do print cleaned form that cleaned data will just print it after this super call that is going based off of you know that standard form view not really going to worry about the invalid stuff just yet so let's go ahead and come back here and I'll just put in an email address ABC @ gmail or whatever doesn't really matter say Justin I'll hit submit and I get a little error here so a couple things I need to adjust and I did this on purpose number one we've got our form here we want to make sure our method is post the next thing we want to do is we want to make sure we have our CSRF token all right so we want to make sure we have that token actually built in to our form so that it's not a get request by default and it has the necessary protection I hit submit this time now it redirects me to form success as we told it to and then I can also see that data that's coming through right so going back into our view no matter what our view is that data is actually going to come through as long as we're submitting that data correctly so it was submitted we were able to get all the information as needed now it's time to turn this into Ajax it's really simple we just go ahead and change whether or not the request is Ajax and then we handle it as such right so if it's an ajax request it will come through as ajax if it's a standard HTTP request that is a synchronous request it will come in as that okay so since we've got this Ajax we also need to import that JSON response so we'll go ahead and do that with from django to HTTP import JSON response that is JavaScript object notation so whenever you use Ajax you have to return JSON you have to return something that JavaScript knows how to handle and that's what we are doing that's why we're returning that response as JSON of course we can add in some other data or other items in here if we want it but we don't need to like we don't need to add in that form data because the form itself or the JavaScript itself would already know what that data is meaning we don't have to send it back there's no real reason to do it the JavaScript doesn't reload at all we're on other cases you might reload to a different page like form success you might need to add that data into context hopefully that makes sense if it doesn't definitely take a look at one of our more in-depth tutorials that cover forms okay so what we've got here now is we have some data that's coming through right so this is pretty standard stuff we might want to use this over and over again so if we scroll down a little bit we have this ajax form mixin now this is just taking all of this stuff out and turning it in to a mixin instead of just right in the view itself so you want to get used to doing stuff like this whenever you see that this might be a redundant or information that we are going to use over and over again you want to get in the habit of creating a mixin so I'll do this as class and this is going to be Ajax mixing and it's going to take an object and this is all we're going to return form it's going to be form related Ajax mix in well it's call it Ajax for mix in as we said here and then again we have to import the actual JSON response so from Django HTTP import JSON response and then we have to change our super call to calling the age form mixin which that means it's going to call whatever class we're in whatever form class were in that is and now what I can do on that view I can just go ahead and do from mix-ins import Ajax for mix in put that in here and we'll get rid of that JSON response we no longer need that so now it's a lot cleaner so if we had ten other Ajax forms on this app we could totally just add that mix in in and it will handle each one the same it's not really doing anything with the form valid or form invalid methods in fact it's still validating the form as the validations would be right so inside of your form you might have validation in here so just define what will clean email takes itself email equals to self cleaned data get email and then we'll say if e-mail equals equals to you know some sort of validation error that we might have so in this case we'll just make it simple if it's email to that we'll do raise forms validation error and we'll say this is not valid otherwise we'll return that email of course this is form data forms hopefully you know this if you don't check out Jago forms unleashed on join CP comm now if we go back in here we refresh and I do ABC at Gmail and some whatever name it says this is not valid so that's a validation that will still happen for Ajax as well which we will show you to test out and of course this isn't actually on the guide this is really just going into more depth so you can see these things in action so with the front end setup we have to make sure that we're using a jQuery version that uses Ajax so by default the standard jQuery library does now of course to do Ajax you actually don't need to only use jQuery you there's other JavaScript libraries out there that will handle Ajax for us so you can do some research on those but something like angular or even react those things can do Ajax for us as well we don't have use jQuery to do it but for us we're using jQuery because it's a tried-and-true method it's really easy to implement as well so for that reason we're going to stick with using jQuery now this case in the docs I put this version of jQuery it's version 1.2 or excuse me one point twelve point four that's what I put on the guide but if you actually looked at our template what you'll see in there is you'll see a different version now this version says dot slim now this coming from bootstrap version four so that's the reason that slim is in there now you just need to get rid of slim because slim doesn't actually allow for Ajax so I'm gonna go ahead and get rid of all of the other things as well and this is going to be the version of jQuery that we in up using and I've got this block JavaScript down here so I'm going to go ahead and copy that bring it into my Ajax that HTML file here and we're going to go ahead and do our JavaScript I'm actually going to copy directly from the guide I'll copy the job or the Ajax call or the JavaScript that we have right here from the guide and before I actually run it I'm going to just change this JavaScript to being JavaScript to block or having it as that block only because I don't want it to run and just yet the other thing is I want to make sure that I have this class installed here as well as this data URL because we're going to look at that right now so i refresh into my join form and I go ahead and inspect the element here and what I'll see is my class is I've got a form class that's cool and then I have a data URL here right so this call right here is from Django and it's a Django template and it's just allowing us to have a URL or the the requested URL being built there so that means if I change the URL by default the submit area or where we want to push this you or this data it's going to be there right so you could change this endpoint how you see fit the next thing is I'm going to just using the post method that's the only method I'm going to be using for this form and then finally I have this CSRF token we I'm going to go ahead and cut the out for a moment and just try out our form we do ABC at gmail which should bring a validation error I go ahead and hit submit and instead I get a CSRF verification failed okay so let's bring that back and we'll save it and we've got that going now what I'm going to do is I'm going to just go ahead and create that block JavaScript again even though I have the reference code below here I'm just going to go ahead and create it from scratch and that way we can talk about each line so first of all I want to make sure it's in a script tag because it is JavaScript and of course being that it is in a script tag we can use it as an external javascript after we're done testing so I'm going to go ahead and do document ready function there we go so this is a standard call when you're doing some jQuery stuff and the first thing is I want to get the data from this form and I also want to prevent this forms from submitting or doing its default method the default method would be sending it using asynchronous requests of course we want to send it using an asynchronous request so to do this I have to select this form by declaring a variable and I'm just going to call it the variable var equals to my form and using dollar sign dot my Ajax form just like this with parentheses and quotes and everything this is going to be that form right so this actually grabs that form and we can do stuff to it right so I could actually add something like my form to add class and we'll say form okay so refresh in here inspect the element and look at my form I've got my class here and it says form if this part doesn't work or is confusing to you're definitely going to want to learn more about jQuery okay so and we do have some stuff on joint AP comm slash projects about jQuery there now we've got our form and it's time to prevent it from doing what it's naturally going to do so to do that we're just going to go ahead and do my form dot submit there's a method on this form called svit default and it takes in a function that can pass in the event so the event being that hey it's being submitted that's the event so it comes in by default you can call it something else you might see it as evey or just E but I'm going to call it events to be just more robust and we'll say a then stop prevent default I save that a refresh in here ABC edge email put in some stuff hit submit nothing seems to happen well nothing does happen because we prevented that default if I comment that out and do it again hit submit it gives me that validation error right okay so we're going to prevent that default from happening instead we want to we want to submit it the way we want to submit it right so I'm going to get the data from this form so save our form data equals to this dot serialize this is the by far the fastest way to get all the data that's in this form so if I take console log of this form data and saved it refresh in here let's go ahead and refresh enjoying ABC put some stuff in hit submit go into the JavaScript console view developer JavaScript console there's definitely these consoles on other browsers but if we go in there we see this year our middleware token we see email and we see name so that middleware token was added because we added that template a right so it's in here input type hidden' name and so on okay cool so we now have this data let's see here I have data and I've also prevented the form from being submitted I also have a URL which is this URL and really am really easily we can just say this URL equals to well we want to get the form itself so my form and then dot attribute and we're going to get data - URL and if this URL was not set as in if it wasn't even there so let's go ahead and cut it out I'm just going to do window dot location and we want to get the window location a trip so the path or the hyperlink reference for that and we can do this a couple ways so I can console.log this URL refresh in here console log I'll hit submit or add to still fill out some stuff here hit submit I get that URL coming through so if you set that data URL right on here to something different data - URL equals to new endpoint you would get whatever that is writes a new endpoint now this case I'm actually going to keep it as join because that's actually where we're sending this form so I hit submit all right at the refresh again and hit submit and there goes it's going to join so that's the endpoint that it's actually going to so now all we need to do we have an endpoint we have data so instead of this URL it's actually this endpoint or that's what we'll call it I know the docs or the guide will say something different but it's technically an endpoint so we have our endpoint we have our data and then we also have a method of course you could go off of the method of the form itself but I'm just going to by default use the post method so now let's go ahead and create our Ajax call it's really simple dollar sign Ajax use the two curly brackets on the inside to set up the HX call method we're going to say post URL and we called it the endpoint here data is that form data and then we want to have success and failure calls so I'm just going to go ahead and copy from the actual Docs even though I have it right in here I'll explain these functions that's just a second there we go my form very good okay so I'm going to get rid of this last block here so we can discuss so if the data comes back a success that is if the form is successful going back to the mix in if it's valid and it successfully sends Ilsan that back if it's invalid it will do something like this now there are other potentials for invalid calls so let's actually take a look at this a refresh in here and do a BCH email hit some submit stuff and I get a 400 bad request well if I actually look back here so say email is not valid so let's do email ABC one two three and then it says form my form preset is not an actual method so this just has to do with the naming it should actually be my form 0 or the array of 0 that's how you're going to go ahead and refresh it so 1 2 3 at Gmail and then something okay so this is assuming that everything's working you might be getting an error what we did outside of this video were some tests on the next and actually required call which is enabling Django CSRF ready Ajax calls so when we do this ajax we actually have CSRF token in the data but it's not validating correctly like it shouldn't actually be validating so let's go ahead I'm going to open it up in an incognito window to try it out with my JavaScript console open ABC at Gmail I'll hit submit I still get my bad request and in here it's giving me the response JSON as well so as we see there's the response JSON and it's an email this is not valid right so that alone is showing me that my error is actually working and it's showing the different errors that possibly could be there but this all is reliant on the fact that my jquery call is really actually not that good but when I submit this data it does say successfully submitted data that's great so it looks like even the validations are working but there is one thing that I'm for sure going to have in here and that's using enabling the step four of this dot this guide is to make sure that we have our cookies in here so I'm going to go ahead and just copy all of this method here and right above our block JavaScript I'm going to add another script in here and just bring it in tab these things in and again this script can be external but what this does is it allows and make sure that our CRS token is inside of our call so if we go back to our form and actually get rid of that CF RF token save it refresh in here I should still get it successfully submitting this data assuming that everything is saved and done correctly okay so that's really all of the Ajax stuff now you can handle these forms because if it's successful if it sends back a successful HTTP status method or HTTP status code that is then it will go to this actual function you can handle it as you see fit of course that data right there is the data that's coming from the backend and then you cannot handle the form error as you may need now of course I'm a descript specifically so it wouldn't be inside of a Chango template so I'm actually going to get rid of this block JavaScript instead go back into base side HTML put another script here bring it in and we're just going to test it on this we don't need two scripts actually so we're going to test it right in here as it should actually work now so save it refresh abc123 at Gmail some whatever name I hit submit and it's successfully submitted to the form data it looks like it's submitted it twice so I'm going to just go ahead and make sure that I save everything and refresh again and there goes it only submitted it once that time the reason I knew it submitted it twice is because it logged this twice so it did the success call two times now again this is best practice you want to pull your JavaScript out and of course even further would be to put this in its own JavaScript file and have it being rendered like an external file using static files as Django which would load static files so so that's the other part that you would definitely want to do prior to bringing this into a production environment that's just that most they're the best practice for doing so and these this code the reason I didn't go through it is it because it comes directly from the Django Doc's and you can learn more about it there hopefully this helps you understand a little bit more about ajaxify any given form the nice thing about this too is now I can actually move this form anywhere and if I explicitly write out the fields that is if I wrote out email field as well as name field I could then paste this form anywhere it doesn't have to actually render form as P the only exception to this would be adding a URL for the URL in here or excuse me not URL but action in here that would go for the fallback that is if JavaScript was turned off we want to make sure that we have our action in there just like we have that data URL but this data URL and this action may be different which is why I had you see those two different things so you can use that as well now the last thing that I'll say is you are going to want to try to do this using the Django rest framework so if you don't know about the January spring work definitely check it out on our projects so you can take a look and learn a little bit more about how you would be using an API endpoint instead of your jane is your standard django views to handle your Ajax requests that is the challenge I leave for you right so if you have any questions please let us know in the comments below hopefully you enjoy this hopefully you've got a lot out of it I will say that if you want to go one step further you can absolutely check out our blog we have all sorts of things in here that will you get better at web development or launching your projects in general the other thing is joining us on YouTube that's join CFE comm slash YouTube make sure that you go ahead and subscribe in there and make sure you hit that Bell and then you also might consider checking out the Django likes tutorial this tutorial right here shows you how to create a like button using Ajax so we will cover some of the same sort of topics but it's not quite as forum level it's much more about likes and how to actually implement something like likes thank you for watching and I can't wait to see you in the next one
Info
Channel: CodingEntrepreneurs
Views: 58,236
Rating: undefined out of 5
Keywords: djangourlshortcfe2017, django 1.11 tutorial, django tutorial, install django on mac, install django with pip, install django with virtualenv, virtualenv, python django, Django Web Framework (Software), Mac OS (Operating System), Python (Software), web application development, learn django, installing django on mac, pip, python package, django, kickstarter funded, beginners tutorial, trydjango2017, 1.11”, “muy, picky”, “django, basics”
Id: zojnkKGRXp0
Channel Id: undefined
Length: 27min 19sec (1639 seconds)
Published: Wed Jul 19 2017
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.