Django forms with Ajax | How to use ajax with django

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi guys this is luke and this video is a re-upload of the fourth part in the django with javascript tutorial series it's an optimized version with images because in the next part we will apply some simple filters to those images just like on instagram so we will bring in opencv to create a pretty cool project but for now let's take a look at what we are going to build in this part so let me select a thumbnail uh to the progress bar tutorial that is available here on youtube on the channel and then we need to provide a name so i'm going to put in progress bar and the description will be progress bar youtube tutorial let's press send and here is successfully saved progress bar and after three seconds it's gone and the form has been resetted so without further ado let's get started so as mentioned before this is a re-upload of part four this is an optimized version that also consists of images so that we can later use it with opencv to apply simple filters like on instagram till this day we've published 11 parts in the django javascript tutorial series the entire playlist is in the description but if you would like to improve the user experience of the forms even more i would recommend after this video to watch how to apply progress bar and how to crop images but now let's take a look at what have i done so far so i started a brand new project called forms approach and i'm currently in the settings py file of this directory and if we scroll down we will notice that the installed apps list has been extended by photos so this is an application that we've created for this project purposes and we'll jump to it very soon and then if we scroll down again in the templates in the dearest position we told django where to look for additional templates so according to those settings i've created templates directory and over here we will keep our base html and then we have also some settings for the static and media files which we will use in this project as well so jumping into urls um this is the urls py file in the main directory here we've imported our one and only view which doesn't consist of any logic just yet we will see it very soon it's located in the photos application of course and below we've included the static and media files in the url patterns so now we can see this photo ad view which is in the photos application as mentioned before so over here we have a basic function view photo ad view with an empty context dictionary that returns render request with photos main html so inside the photos application we have a templates directory inside we have a photos uh folder and here's our main html so this is this directory photos main html and here we are passing to this template the context dictionary and then we have our main.js and we'll take a look at it in just a second but first let's go to base html over here we have a html template that consists of our custom js and here we are linking up our main.js so if we go to the settings py file over here we have static files years and according to those settings i've created a static folder and placed over there the main.js okay so and this is for the custom js then we have jquery bootstrap css and also required meta tags and then we have the title which is ijux forms and then we have diff class container with margin top three so this is these are the bootstrap classes and inside we have a blog content for template inheritance purposes so now if we go to main.js we have only hello world and in our main html we have here hello world as well so the end result is that we see hello world over here in the browser and we see hello world also here in the console all right guys so right now we can jump into models py file create our model and then based of this model we will we will create a form so let's create a class photo photo which inherits from model stock model and we will have um we will have three fields four fields let's see first of all i'm going to say name is going to be the first field and this is going to be a model's char field with the max length of let's say 100 and the other one is going to be the description so i'm going to place over here a model's text field and we will also have an image and this is going to be a model's image field with the upload to upload to images and did i create a media folder i created a media folder as well so if we go back to the settings py file here is our media root based your media and this is the place where we are going to keep our media file our images however in the media directory we will have another one that is going to be images okay and let's also add a created and this is going to be models date time field with auto now add set to true and let's return string representation return str self name all right so now we have created our photo class and let's create another file in the photos directory which is going to be forms py and we will begin by the from the import so from django import forms and from dot models we want to import our photo class and over here let's define a class which will be named photo form and this will inherit from forms dot model form and with class meta we are going to indicate that the model is going to be the photo and the fields are going to be the let's put the image first and we'll put the name and the description all right so now i'm going to save this and i'm going to jump back to views over here i'm going to import this form so from dot forms we want to import photo form and here let's put form is equal to photo form and this will take a request post or none and request files or none all right and now we can we are not done of course with this view but right now what we can do is to pass this form to the template okay so right now i'm going to save this and focus on the main html so on the html part let's jump to main html let's delete the hello world and then over here we are going to need a couple of things so i'm going to begin with a div class of let's add a margin top three again and then inside let's put a div class or div id and let's set it to alert box so this is the place where we are going to display the alerts so it can be either a confirmation that the form has been sent successfully or uh some kind of a notification that something went wrong and then below we will have a preview box so i'm going to call it maybe imagebox so here we are going to see what image we are willing to upload and then we will place our form and this is going to be and the method actually we don't need this we just need to focus on the id because the rest we will set with ajax so i'm going to put in the form as the id and then i'm going to close up the form and over here what we need to do is to put in the csrf token and also we need to put the form itself so let's put form sp and let's save it and let's take a look at the results so the form isn't looking that great and in order to change this we are going to install django crispy forms it will take only a second so i'm going to quit the server from running tip install django crispy forms and by the way we didn't do python manage py make migrations and python manage py migrate okay so let's do this very quickly and python manage py run server again okay and as the next step we need to add crispy forms to the installed apps list so in the settings py let's jump into installed apps let's add crispy forms let me copy this again sorry about that crispy forms all right and we finally need to provide the crispy template back so i'm going to copy this as well put it maybe somewhere over here and over here crispy and change uniform to bootstrap four all right so i'm going to save this and then we need to go back to our main html and load load crispy forms tags and then over here instead of form as paragraph we are going to put in the crispy filter i'm going to save this hit refresh and there it is so this is looking pretty nice okay so we can proceed let's also add a submit button in the form section so i'm going to put in button type submit and class is equal to btn btn primary and so it's going to be a blue button and here i'm just going to put in sent and close up the button all right so let's save this again refresh and there it is okay so right now we can actually focus on the javascript part we need to grab all these elements necessary for completing our project so let's jump directly into main.js and i'm going to get rid of this hello world and begin by grabbing the alert box so let's put an alert box and this is going to be document kit element by id alert box and then we'll have the image box so this is going to be emg box and document get element by id and emg box and we also need to have the form so i'm going to create another variable called form and this is going to be document get element by id and form p form actually because this is the id and what else well we'll need to have the inputs so in order to do that i'm going to first of all console log the form let's see what do we have over here and it seems we don't have anything let me do it one more time command shift r okay here is our form and if we take a look inside here is our input type hidden with the csrf middleware token and then we have some and divs with some ids and if we take a look inside we have inputs okay so here we have input type file name image and here is our id so for the image for this particular field we have a id image and then if we go inside this one we open up we have input type text and here is id name so the convention is the id dash and then the name of the field so this is id image id name and id description so knowing that let's get all of those inputs so this is going to be const name and this is going to be document get element by id and we want to grab it by the id name then we will have const description and this is going to be document get element by id and here we will have id description and over here let's put in const image and this is going to be of course document get element by id and then id image all right and let's also grab the csrf token so i'll put in cons csrf and we will grab it not by the id but document get elements by name and here we need to pass ncsrf token and let's console.log csrf let's save this hit refresh and here we have a note list so if we scroll all the way down here is the value with the token so we need to keep in mind this when we are going to add the csrf to the form data so i'm i'm going ahead of myself we will do this very soon okay so right now if we have all the necessary elements actually we can also create a cons for the url the url is going to be blank because it's going to be the same path so right now what we can do is to display the image so we will show in the image box the image that we want to upload and we can do it by writing image add event listener and we can put in change so on the change event we are going to execute something and what we want to do is to create a new variable called emg data and this is going to be we need to grab the image itself so image files zero is the way to do that and then we need to create a blob object for preview purposes so const let's call this url and this is going to be url and then create object url and we need to pass in this image data and right now we can console log our url let me refresh and let's test this out so i'm going to select an image and here i have a progress bar thumbnail and let's open it up and here is our blog blob object okay so right now what we want to do is to actually refer to this image box that we have over here and to the inner html so we can write down image box in our html and we want to display this image so i'm going to use backticks for this emg src and over here let's use the dollar sign inside the quotation marks pass in the url and then let's also add a width of 100 percent and then let's close it off and let's try this out so i refresh the page i'll select the progress bar thumbnail again and there it is so this is the preview and here we can see the image that we are trying to upload so right now let's focus on actually saving the data so we will need to refer to the form and add another event listener this time we are going to listen for the submit and if this is the case we are going to do some stuff so first of all let's do event prevent default so we don't want the page to be reloaded and then we can create a variable called fd that stands for form data and here let's put in new form data and to this form data we want to append some things so first of all let's take care of the csrf so over here we need to put in the csrf middleware token and we need to put in the value so csrf and then zero dot value and then let's take care of the name so we have form data append name and here we need to refer to the name value so let's put a name dot value and this works like this that we simply need to put all the necessary inputs of our requests so we are expecting the csrf middleware token we are expecting the name we are expecting the description we are also expecting an image and to those fields we need to assign some values and this is exactly what we are doing we have csrf middleware token we have a value we have a name with a value and we also need to put in form data append description [Music] and let's put in description value and we also need to have one more form data append image and this is going to be image files zero okay so right now we have all the necessary fields added to the form data and we can use ajax so let's put in ajax and first of all we need to specify the type so it's going to be post as the next step let's add a url and we can assign the url from over here then we will have to specify the end type so this is going to be the multi-part form data we are sending images so we need to have this end type multi-part form data and then we put we will put the data itself so this is going to be the form data that we created over here and we will have what will happen on success so for now let's put in just a function which takes in a response and here we will simply console log the response and if something goes wrong we'll have an error and this is going to be a function that takes in an error and it console logs this error okay and then we'll also need to set the cache to false the content type to false as well and process data to false okay so right now we can actually go ahead and save this and we can jump back to our views py so over here we can do a check if request is ajax and if this is the case we can do another check if form is valid valid and if this is the case we are just going to put in form save but then as a response we want to return a json response so let's import it from django http we want to import json response and let's also have a data dictionary which is going to be empty initially but then if we have request is ajax and if form is valid we can add something to it so for example we can add a name and this is going to be data name and let's put in form cleaned data get and let's put in the name and let's also add a status data status and let's put here just okay and then we want to simply return a json response and pass in the data all right so let's see if this will work there's one thing missing actually because we forgot to register the photo in the admin so let's do it very quickly from dot models we want to import our photo model and here let's put an admin site register and let's put in photo okay so now i'm going to save this i'm going to jump to the admin hit refresh and here we are so we are going to check if this is working or not so let me hit refresh let me select the file let me put in test test and then let's present and here we have name test status okay so it seems that it it's working let's hit refresh here's our object and we have test test and here is our image so perfect this is working very very well and let's continue working on this in the main js part so we will have some alerts as a confirmation that everything is okay so this is the next thing that we are going to do below the url i'm going to add an arrow function cons handle alerts and this will take in a type as well as text so over here let's put in let's refer to the alert box so we need to put an alert box in our html and we are going to implement some html code with the use of backticks but what we need to do next is to actually go to getbootstrap.com and select some alerts so i'm just going to grab the one over here it doesn't really matter which one you select because we need to do some adjustments so what we need to do is where we have success primary secondary we need to inject the type okay so let's delete the success and again i'm using backticks so this way i can put in a dollar sign and then put in the type and over here we are going to delete this text and put the text that we will get from over here from over here to be more precise so again dollar sign and text all right so since we have this handle alerts function we can actually use it so i'm going to copy it and go all the way down and first of all let's implement it over here so we will have handle alerts over here and also let's put it to the error section so to the error section let's maybe begin from over here because it will be much more easier as the type we want to pass in danger and here as the text let's place oops something went wrong wrong all right and then over here what we need to do is to pass in as the type success so we want to have a green alert here it will be a red one and then over here we will have something to do with the response so let's create another const let's call it success text or as text and this is going to be again with the use of tactics so i'm going to put in success fully successfully is it with 2l or 1l i'm going to leave it like this successfully saved and then let's put in response and if we go to our ajax form here is our response and we want to refer to the name so let's put in response name okay successfully save response name and right now we need to pass in this s text to the handle alerts so let's save this let's refresh and let's also do one more thing to the form so we need to jump into main html and here i'm going to put in auto complete and set it to off okay let's hit refresh and this way we don't have a history over here with the name field so i'm going to put in test 2 test 2 the description and i'm going to select the same image and here is the preview and let's press send and successfully saved test2 and then if we jump to our photos here is tests2 so this is working okay so let's change the url for the one that doesn't exist i'm going to put in sss something like this hit refresh select a file so the previous should be would the preview should be working and it's working but if i put over here something and press send then we will have an error over here and a red alert above the image box so oops something went wrong okay so this is working so i'm going to bring the bring back the proper url which is a blank url save this and right now we can focus on resetting the form if everything is correct and in order to do that we are going to use a set timeout function so somewhere over here let's just put in set timeout and after for example two or three seconds we want the form to be resetted so let's put over here the time the time let's set to two seconds and then what we want to do is to refer to the where is the alert box and we will begin by setting the alert box to blank so alert box in our html after two seconds the alert should disappear then let's also set the name value to blank let's also set the image value to blank and the description value to be blank as well so now i'm going to save this and let's see how this works okay successfully saved and then it's gone and the form is reset however we forgot about the preview box so our image box and let's do this very quickly emg box and inner html let's also set it to blank all right let's save this let's try it one more time another test let's select the file the image and let's press send successfully saved another successfully say saved aaa so maybe let's do three seconds let's try it one more time a test let's press send successfully saved aaa and right now the entire form is reset and of course the objects are stored in the database so yeah i think we can finish off over here we will continue from this moment in the next part where we will apply filters to those images so we will modify them with some simple filters and maybe not so sophisticated like on instagram but we will use some basic operations in order to modify our images so hope to see you in part two if you enjoyed this video please subscribe to the channel have a great day and bye bye
Info
Channel: Pyplane
Views: 19,576
Rating: undefined out of 5
Keywords: Django forms with Ajax, django ajax, django ajax tutorial, ajax django, django jquery, django ajax request, django ajax post, django ajax form, django ajax form submission, django form tutorial, django form without page refresh, ajax in django, django ajax csrf, django ajax tutorial jquery, python django ajax tutorial, django ajax post json data, django ajax post data in view, Django ajax post with csrf, django ajax image, django ajax image upload
Id: C4fr3SCqgJQ
Channel Id: undefined
Length: 34min 29sec (2069 seconds)
Published: Tue Nov 10 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.