How To Work With Ajax In Django Using Vanilla JavaScript | Submit Form Without Refresh

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

That's right.

👍︎︎ 1 👤︎︎ u/MariaGonzaless 📅︎︎ Jul 27 2021 🗫︎ replies
Captions
hello my good friends welcome to another django video today we will see how to use the javascript fetch api to send an ajax request so we will adjuxify django without using the jquery library since most tutorials cover only using the jquery when it comes to using ajax in django so we will see how can how we can post comment a synchronously without reloading the page if you are ready let's get started this tutorial will have three parts the first one i will explain briefly how to fetch how the fetch api works with a simple example the second part i will cover the installation of django and the creation of the models the last part where i show how to use the fetch api to send an eject's request feel free to check the timestamp in the description and jump to the part you need to know about to understand how the javascript fetch api works let's try with an example let's get data using the fetch api i will be using node.js to execute the javascript file i hope this will be a bit clearer than working with an html file and opening the console of the browser okay as i said working with fetch is very simple you need the url to fetch then you get the response and you can catch any error during the handling of the request in this example we will get a random codes from public api that gives us a random anime code it shows how a basic fetch request is really simple to set up for now let's simply print our response as it is then if we face any error we can print it out let's save from here but before we save i want to mention that node.js doesn't support the fetch api so we need to import it over here then install the package using npm install node fetch now we can execute our js file as you see here once the request successfully requested the resource is available the fetch method returns a promise which will resolve into a response object as i said the fetch method returns a promise so to get the actual data from the url we fetch it you call we can call the json method this means that the dot then handler will take the resolve the response and converts it into json which means we need a second then handler that will give us access to the actual data let's just see the data for now save and run the script as you see the fetch cached an error which is almost a spelling error actually this should be console try again now here we got our data it's a javascript javascript object we have the anime name the character and the code of that character each time we launched the script we got another random object now we need to create an html file to see how the fetch api allows the browser to load data synchronously so we create a new html file open it with vs code in the body section we create a new div we give it anime id and we need a button to execute the javascript function each time we click on it it will display the anime code without reloading the page and open a script tag we simply write the same code fetch the url then get the response object convert it into json object then we handle our data first let's get the div where we will display our codes now we simply added the code inside that div in case we face any error we can alert it this time now let's save and open this with the live server here we go if i click here we got a new code each time we click we got a new random code without any need to refresh the page for the get request we don't need to pass any option to the fetch method it's a simple get request to get a json content of the url we will pass but this will be different with the post method which we will cover in the comment part of the jungle this is the design of the comment section we will work with i created it using html and css it has two parts a place where we display the comments and the other one is for the form i try to make it responsive with the minimum of the code and the result is satisfied it's quite responsive it looks okay for both desktop and mobile devices i will include all the code with explanation in one article you will find the link in the description below now let's jump into the real work the installation of the django will take time so i will use a script that i made to create and install jungle for me quickly now i will go to the github repository of the script we will use you can find the link in the description as you see it creates a virtual environment and setup junk automatically for you we need to clone it first in this folder now the first step is using the script to create a virtual environment for us as you see it tells us about the system we use the python version with the pip version too then it's it installs the virtual environment created a new one then activated once it's done finally we use the third command line to create a jungle project we choose the project and the app name here then it creates a new jungle project and set up the comment up inside of it with the configuration of the media and static files it will do everything we need to run a django project once it's done it will run the server we go to the browser and check it and we should see this message now let's replace the content of the home page with the comment section we created over here we need to load the static tag and the source should be loaded using the static tag provided by django this is how django serves the static files now refresh the page we see an error a spelling error here load refresh again and here we see our home page then the first thing we will do we will think about is where we will save our comments for sure in the database for that we need to create a comment model in this model we need to specify the author of the comment it is a following key so we need to create another model the author model which also we will link it to the django built-in user model we give it another field full name with max length of 50 characters and the image of the author which we need in our comment section the str function here defines the way we see the model in the admin page i want to see the full name instead of object one or object two okay we're back to the comment module we need a field for the command content which is a text field and a date field with auto now added set to true we won't save the date manually for sure same thing the ostr function let's display the first 50 characters of the comment and we need to use the data class to order the comments you can do it from here or from the views as you want the next step is adding the model in the admin dot dot means dot p wi-fi we need to import all the two models we created then admin.site.register then type each one of them and for sure after creating any new model we need to migrate the up we run make migrations then specify the app name author then migrate this will create two tables one for the author and one for the comment and we need to create a new user since we can't comment without we login then around the server let's go to the admin page login first let's create a new author it will be my name i have an image here save it same with the comment i will create a new random comment with the author created right now then we need to get the comment we saved and send them to the template we do so using the views.p wi-fi first we import the models we already have a basic view that renders the home page inside of it we need to get all the comments then create a context dictionary that holds these comments and pass this dictionary to the render function so we can get it in the template now in the template we have the same div duplicated we need only one and we then loop over it i will change this to jungle then for loop for comment in comments this should be the author's image then the author's name we pass the field the title filter since it's a name display the date add the date format and finally the command content we see an error here that should be context not comments let's refresh and here is the only comment we have now we will see how ajax provides a way to send the poster quest to a jungle view and receive and and receive any return data without any need to refresh the page we need to get the form element but first let's update it role is form method is paused and pass the csr of token tag for the csrf protection which is required in any post form in django then we give it an id which we will use here to get the form element then we added an event listener to that form and each time it is submitted there are some work we need to do for now let's display anil alert to see if it is working go to the template fill in the form and submit and we see the alert back to the template actually we don't need these two submits only the message since we have a user that will comment then we need to get the message content since we will send it to the backend using the fetch api so i will check if we get it the right way let's submit the form again and we can see the message in the alert which means everything is working fine now using the fetch api for the mandatory argument which is the url we pass the url of the home page then test the fetch api i will print it i guess it won't work for the firefox browser i have the fetch api is newly invented so it's not supported with some versions of some browsers for the internet explorer it doesn't support it at all when it seem well it seems that it works now we need to pass more arguments inside beside the url of the fetch method we need to pass the method so in order to make a post request it should take the value of the post by default and in both fetch api and xml http request browsers will not send credentials so we need to set it manually in the options of the fetch for the headers which are wrapped in a map like object that reads its keys note that we are going to send json we need the headers options to send the x request with is very important so in the views we can know that we have an ajax request also in the headers we need to include the csrf token to prevent cross site request forgery attacks fortunately javascript provides to us the code we need to add it to get the token from the csrf token cookie i will add it quickly over here and now we need to send the message content to the backend so we use the json.stringify to send the javascript object as a json object to the views file we can include files or other data form but for our example we need a simple json object and in the first then handler we convert the object we will get from the backend and create another then here we will display the data we in the template moving to the views.py file we need to handle the request we got from the fetch api instead of checking if the request method is paused we can't check if the request is ajax we do it this way that's why we specify the x requested within the headers of the fetch method we print this message for sanity check this time i will open the chrome browser fill in the form submit and let's check the terminal and we see our message so everything is working in that case we can't get our message we use json to load the request then we use the comment content we got from the template to save it in the database we create a new comment instance we pass the message and the user which is the logged in user then we save it let's give it a try write a random comment and submit let's check the admin page we can't see our new comment let's check in the terminal we see an error i guess i know the reason of this error this should be author note user save and try again added a comment again and submit go to the admin page still we can't see it check the terminal again yes we need to login we open it in the chrome browser without logging in also we need to get the author object from here we got it using the logged in user now this should work and yes it does we can't see our comment here the page has been reloaded we will fix that in a few seconds so we can comment without refreshing the page the real work is now after saving the comment model we need to send that comment object to the template asynchronously via the fetch api we can import the serializer and convert the entire module and send it to the template but to make it simple i will create a simple python dictionary that holds the data for us the author the author's name the image you are in the content and the date and we can choose the date format from here if you want then using the json response which will convert our python dictionary into a json object and send it to the template okay now in here let's console.log the content from the data we got from the backend let's refresh the page write a comment open the console then submit we can't see anything here even i am sure everything is working right anyway let's try to print the content in an alert and over here let's change this we prevent the default action of the forum so we don't reload the page each time we submit the comment form so if we refresh now and pause the comment you will see the oled that holds the content of the comment and here and there is no refresh of the page but we can't see the comment unless we refresh so let's fix that right now so instead of alerting the content we need to display the newly added more comments temporary we need to create this comment div but in javascript so we create a div first then we added the comment class to it to make it quickly i will create a string that holds the entire div we need to replace the double quotes with single codes then we need to make it in one line after that we have to update the four variables we have in the data object so now we set the inner html of the div we created it takes the string over here and we need to create a div as a reference we give it a temp id then in here we need to get it using that id and simply we insert our newly added comment just before that div just above the old comments let's save and give it a try added a new comment and post it we can't see it which means we have an error let's back to the template let's see this should be temp let's save and try again added a new comment submit and here we see it and the page didn't refresh so everything is working we have only two issues first we need to empty the form after we submit it we do it using the reset method and in the views file we need to reformat the date in a similar way as the jungle time format give it the last try submit a new comment and here we go they are not the same but looks better than the previous format that's it guys i hope you enjoy it thanks for watching and don't forget to give it a thumbs up and especially don't forget to subscribe for more videos like this see you soon you
Info
Channel: Selmi Tech
Views: 637
Rating: undefined out of 5
Keywords: how to use ajax in django with vanilla javascript, fetch api django ajax, ajaxify django javascript, submit form django no refresh, comment form django without reload page, submit a form in django without refreshing the page, use the fetch api in django, how to use the javascript fetch api with ajax in django, ajax django crash course 2021, django ajax tutorial, fetch api django example, django javascript ajax
Id: p6-mzw0bEGA
Channel Id: undefined
Length: 38min 17sec (2297 seconds)
Published: Sat Jul 17 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.