Learn Django - An AJAX Like button feature within the Django Framework - Django Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello and welcome to part 10 of the django project building a simple blog so in the previous tutorial we created a favorites feature for users to add their favorite posts to their favorites list so we utilized a url system and the page had to refresh in order to make that feature work so here we're going to go and now build a like system utilizing ajax so it's going to be it look a little bit more seamless so won't have to refresh the page to actually perform an action so this is a very simple process again it's going to be very similar to the previous tutorial we're going to need to make a new model field to facilitate facilitate this new feature then we're going to update the template and i've made a new template for this building the blog series and then we're going to create a new url and then develop the view so like i said i've updated some of the graphics for this building the blog series now and we now see that our post looks a little bit more like a a real post in a blog so on the right hand side you'll notice also that i've updated the graphics here for the add to favorites feature so when i click on here a little tick appears so these are just bootstrap icons that you can get from the bootstrap website and when you are saved remember that when we did save the post it goes to our users saved post and we can remove them so that was in the the previous tutorial so in this tutorial we're going to make this like button here so when the user clicks on it it literally just adds a new like to that post and of course if we refresh the post it stays there uh in this tutorial we go ahead and just set it up so if the user clicks on it again it just removes their like from that post so it starts off as we always do in this series by utilizing the previous code from the previous tutorial if you don't have a copy of it and you want to start from here then just have a look in the description you can download it there's also a video on how to get it started when you do start the code from the previous tutorial this is where we're starting this is the code where this is where we left off in the previous tutorial so we had a post and we had an add to favorites button you've seen in the preview that i've updated that and also the code here of updated with the different fonts we're utilizing now so we'll go ahead and add that into this tutorial and we'll go ahead and make those changes i won't go through every line of styling and because our focus here is on django predominantly but i'll give you an overview of what's happening and the code is in the repository and the code repository which you'll find a link to in the description of this video okay so let's get started first of all we're going to create our new fields in our model to facilitate facilitate this like system so first of all then you need to head over to the blog so we need to adapt the blog model and inside of here you'll see that we've got a growing post model right here and then in previous to in the previous tutorial we created the favorites field so now we're going to do a very similar thing building another many many-to-many table or sorry field uh connecting the likes to the users so what we're trying to do here is that we're going to create a a new field that's going to connect a like field to the users field so that we can store which users have actually liked this post so that's useful because we can when we open the post we can see if the users liked it or not and we can then perform an action based upon whether they have liked it or not so we might want to change the graphics based upon whether they've liked the the post or not okay so inside of the blog models there's three things i'm going to add first is an image caption so i want to just add a facility where i can attribute the image so i'm just going to make a little character a character field here um with max length of 100 with the default or photo by blog so here i can if i'm using an image in my blog i just want to attribute someone image i can just utilize that field so that's just a bit of a side track but i've added that to the um blog now so down here you can see we've got on line 47 and 48 we're going to add two new fields first is the likes field so this is the connection that we're building the many to many connection between the post and the users so i'm going to be able to capture which users have liked this post and like i said i can use that to perform different actions secondly i'm going to create this like count field it's just going to be an integer and i'm going to save how many times someone has liked this post so that's just an additional feature and we'll have a look at how we can update that utilizing a query so you can just go ahead and make migrations and migrate so the manage pi migrations oh i spelt that wrong i need an s and then you see that we're going to add three new fields and then we can go ahead and just migrate and there we go so next up is then updating the template so we're going to add a new icon well we're going to make a few changes to our template as you've seen i've added a new stylings and new styling to this single post so we'll do that and in addition to that we add the functionality for our like system so now we need to head over to the templates i'll just close that down the templates and we then need to select the blog and then the single page so let's first of all i'm just going to add some more styling so i'm not using a style sheet here simply so that you can see what styling am i using on this page so i've imported some fonts here from google fonts and we're going to be utilizing this on a single page i've overridden some of the bootstrap facilities here so h1 here you can see that i'm going to use in pt serif font and h2 as well i'm overriding with a little bit of letter spacing and font weights and so on also the p tags i'm updating to utilize a new font and a line height and so on and this was there before and then we're going to be utilizing an avatar for the user as you saw in the preview we have like the the user of the posts image and then just creating some smaller text here so i've just added some styling for that okay so i've added this new structure here but what's important and to focus on this like system is i've added two items so first of all i've added this span here with an id of light count and within here i'm just gathering the post data and inside of that we should now have a like count so in the model remember we created a a like count a light counter so i'm just basically extracting that information from the post data i'm going to put it right there so next up i created a button this could just be a link i've just created a button for this and you can see that i'm wrapping this around or musing the bootstrap facilities here text dark i'm making it into a button into a link i've given it a border of zero and just removing all the bootstrap styling so button outlined light because bootstrap normally has some sort of shading around buttons so that just removes that and inside of that you can see i've created a value so this is important so i'm making a button here which i'm going to submit and i've hard coded the value which is the post id because what's going to happen with ajax is we're going to send a request to the server and we're going to send the actual post id along with that request and then we'll use that id to actually update the correct post so that we know which post we're actually liking so you can see that i'm using this svg if you want to access that just so head over to bootstrap and go to icons and there's a whole list of different icons here uh just search for heart you can see that i'm utilizing this one here so i've just copied the code right here and i'm utilizing that i have made a few changes just the width and the height so i've just scaled that slightly and i've just lined things up using padding zero as well okay so we created this button it's got an id so we can utilize this now as a button and detect whether someone's clicked on it so what we're going to do now is go over to the ajax we're going to detect based upon if someone clicks on this on this button remember we're going to use this id like button and remember that the value that we're going to capture from this button is the post id okay so at the bottom of the page here we've below the this is the code or the the javascript for the uh the comment system that we built in a previous tutorial so underneath that we created this new set here so we are using jquery so with jquery the code is going to look slightly different from vanilla javascript and in addition to that if you're using the bootstrap template you need to remember that i think the default template doesn't have the correct jquery version so what you're going to need to do here is go over to your base template or in my case it's the base template at the bottom normally the bootstrap template comes with a load of scripts here so what we're going to need to do is just remove the jquery at the bottom here because we're using the slim min and that the slim doesn't come with the the ajax functionality so we just need to remove that and we then we need to update that with the with a new version and we need to add it before we actually run the code so we're going to need to run it at the top here so we just drop it in there okay so this is a 3.4.1 jquery min which does include the ajax functionality okay so heading back to the single page so now we can go ahead and create some ajax or an ajax call so we go ahead and we say okay look in this document and then on click now that is a little bit broad potentially you might want to uh refactor this later on but we're saying on click where the id equals like button so remember the button we created we gave an id of like button so when someone clicks on that button we're going to perform an action so the action is we're going to create an ajax call so we're going to create a post type so we're going to send we're going to send a post request and then we define the url that we're going to send this data to so after this we'll create a new url for this and we're going to call that like so we're going to send that data to there obviously the url is going to be connected to our view which is going to perform all the logic okay so next up we're then going to send them data across so what we're going to do is send a value that we left in the like button and remember that's the post id so we're going to send the post id to the view where we can then perform some actions so because we're sending a post we're going to need our csrf token so we set that up and send it across as well as the data and then we then send it off for the action post okay so that data is now being sent across so let's now go ahead and create a new url and we'll come back and have a look at the code when the data returns so remember we're sending it to account so we need to open up the accounts and go to the urls so we're now going to just add a new url for that okay so it's a really simple one let's just add it below the favorites you can see here that we're just going to add a path to like and then that's going to be the views dot like and then the given the name of like so just remember in the singles here we're referencing that name like right there so that's how we know to include this path right here and that's how we're kind of injecting or utilizing that url so now we have the url we can now go into the remove that so we can now go into the account and have a look at the views so now we need to build a new view for this like system so in order to actually like a post the user has to be logged in so we're going to use the login required decorator again and just make sure that you've imported that in so i've imported him right here so now we're going to create the view so this is going to be a very simplistic view i just wanted to go through the logic here and we'll spend some time later in another tutorial looking at how we can improve this potentially performance wise so let's create a new function here or new view so we're going to call this like so first of all we're going to check to see if the action has been performed so we're going to say if request post dot get action equals post which it should do then we're going to set up a new variable called results because we want to return the results back so what we want to return back to the user is the updated number of the amount of likes that posted has had so we just create that placeholder for that and then we go ahead and actually perform a query to find the post data based upon the post that the user is trying to like so here we create a new variable we um just create that into an integer it's going to be a number and then request.post.get post id so that was the data that we sent across in ajax the post id so that matches up with uh where we that matches up with the data here um called post id so that's what we're matching up here remember we're putting the value inside of that which is the value that we injected in the button so we're capturing the data it's inside of here and then we're putting it into this id variable so that's going to hold the id of the post so now we have that we can actually run the query sorry so we're going to get user get object or 404 just make sure that you've imported that into your project at the top here so we're going to do that and we're going to get the post that's equal to the id of the id that we sent across from ajax so now we have that individual post now we can perform an action so what we want to do now is obviously add up or so we want to add on a new like or remove a like uh from the the existing amount of likes the post has and we also want to add the user to um the likes list so that we can add up or we can um we can see who's actually liked the post so two operations here so the first one here is we're going to create an if statement what we're doing here is we're checking to see if the user has already liked the post so we specifically select the likes field and we run a filter so here we're going to check the id so the user id if someone's logged in we'll be able to capture their id if it matches an id that's already inside of this likes field then we're going to create a match it's going to exist so if it does exist what we're going to do is we're going to remove them from the likes list in the table so we now removed them so they aren't liking this post anymore we additionally or sorry we we also get the post lite data the like count data that we set up remember we made a like count field in the database and we basically just take one away from it so we're performing two actions we remove them from the likes field and we also then take away a number or remove one away from the current amount of likes the post has so once we've done that we can then create a new variable here and we're going to populate that with the current amount of likes the post has so remember here what we're doing that the data is in memory okay so this post data is memory we've removed um we've gone into that those fields and we've removed one already from the amount of likes so now we can get the updated amount and store it in the result and we pass that back to the to the user or to the page so we'll pass that back in a minute so we got that and now we can save the data so like i was suggesting this isn't the most efficient way particularly when you're um creating or doing calculations on a table i just wanted to show you some basic logic for this so it's worth having a look at f expressions so have a read through that and see if you can adapt this to use f expressions it's a lot more efficient and safer to utilize than the code that i'm going to be utilizing and showing here but like i said i just wanted to show you the the basic flow to get you understand of what's happening okay so now we've got that in place we're now running else so this else represents if the user hasn't liked this place before so we've got this if statement here so now we're saying well if they haven't liked it we're going to do something else so what we're going to do here is say post likes add request user so we're now going to add them to the the field and in addition to that we're going to get the likes count and add one to it and then obviously save that in our variable called result and now we have the new updated likes amounts for that post and then we go ahead and save okay so now we've done that now we're going to return something so based upon um the current position or the current user state whether they have liked it or not before we're now going to return the result so this result that we're returning is either going to be plus 1 to the post count or minus one to the post count okay so now we've got that logic in place we can now go back to the single page and we can have a look at the success so here we set up the post the ajax post so now we've got an action which is a success so if we do have a successful return from the uh call then we can now do something with it so what we do is that the data appears in this json variable here which you can change i've just called it json so our data return from the view which is obviously the result number has been returned here in json so what i can do now is i can update the light count uh element so what i'm doing here i just zoom up right here go to the top uh we've got the we've got an id here called light count and when the page initially runs it puts the light light count amount in there so maybe 10 likes or 100 likes or whatever so what we're going to do is we're going to get this element and we're going to update it with the new amount so traveling back down here again you can see that what i'm doing here is document.elementbyid so it's called like out the id in that span and then i'm going to get the inner html and then update it with the result so i go inside of adjacent data that's returned i've referred to it as json and then go inside of that date and i specifically pick out the result which should be the new number of the amount of likes the post has had and that's going to then inject this number into that span at the top okay so you can also log it as well if you want to see what's being returned and there's an area here if you want to create something there so that's the main functionality of this we've pressed the button we've sent a method across we've dealt with the functionality of adding the user removing the user and then adding to that count okay so next up this is just a follow-on from the previous tutorial but if you remember we've created this area here where only users who are authenticated will see so this code will only run here if the user is authenticated they're logged in so what we've done here is i've just extended it with a a new element here and inside of this as i told you earlier we've got the items here for that icon for the heart icon and also for the the number system so we can we can only see this item if we're logged in now we obviously want to see this feature if we aren't logged in so this is an if statement here so if we travel down down here we've got the else so if they aren't logged in we're going to perform this action so what we're doing here is we've just copied and pasted the code but this time what we've done is that we set up set it up as a link so i just wanted to show you that you could set it up as a button or a link so now i've set it up as a link i've added the accounts register link like i did with the previous icon so that when users aren't logged in but they press the like the the heart icon the like button then they will get taken to the register page they will then register hopefully and then they can start liking your posts so have a look at the code in the there's a link in the description to the code have a look at this code have a look at the flow the ifs because there's another if here so this is just a nested if notice that we have else and then we end that specific if and this else then represents the first if here if you're a little bit confused or new to programming okay so let's go ahead back into our our system now refresh i probably haven't turned the server on nope okay let's turn this over on maybe there's an error no so i run the server all okay and i refresh you can see that i've got all the the new functionality here notice there's a few issues here we'll deal with those in a second so i'm not logged in and you can see that i've got access to these buttons i press them it takes me to create account similar to the add bookmark or add to favorites it takes me to create account okay so that's function is working okay so let's go ahead and log in as admin and admin so i don't currently have any saved posts nope okay so let's go ahead and save the page just make sure it's working yep that looks like it's okay so now let's go ahead and like this and it's not working and i just remembered why that is so let's go back because i've forgotten something here so notice that we didn't receive any really error messages if i go into the console um oh actual fact there is apologies and this is really simple so the name errors name json response is not defined so this is a really simple one to fix um i'm happy to show you the errors rather than me just just skip them and just fix it and tell you simply because you're gonna receive errors so something like this if you error name error name json response is not defined the first thing you can do is have a look at the views and the json response requires an add-in so we need to add this feature in so what we're going to need to do from django http we're going to need to add in the json response so let's go ahead and do that and make sure you save let's just go back to the page and press the button and there we go so if i press it once obviously it goes up if i press it again remember that i'll be saved to the the likes table so it recognizes i am saved and then obviously it will take one off so there we go so that's all now working okay okay so apologies for looping around but i just want to just summarize what's happened here so when the user isn't logged in they will see the buttons and get taken to the login page where they have to register sorry or log in okay so that's the first thing second thing if someone is logged in and they haven't liked before then as soon as they press the button they'll be added to the table their user id will be added to the table of likes for this particular post and this number here will get incremented so that was a new field that we created remember um in the model in the blogs model we created two fields so the likes count will be added or one will be added to it obviously then when they click on this again we obviously will do two things remember we remove them from the likes table and we also then take one away from the like count okay so hopefully you got to the end if you have thank you very much hopefully there was something there something new that you've learned so this was a slightly different approach to presenting code for you there was a little bit a lot of assumption there i didn't cover every single style element that would take a long time and then really this is a django project so i try and concentrate on the django if that isn't something you like then please let me know if you are stuck with a code if you're completely new and you're trying to develop this and there's just too much code here and you're trying to work out what's going on maybe i can develop another tutorial which breaks things down a little bit more so hopefully you're in control so please let me know what you need what you like and i try to accommodate you as best as possible so next up we're going to have a look at um uh shapely a fairly quick one we'll have a look at media and static and how to serve both static and media in the same project so static files are things like css pages and images similar to that the media folder that we've already covered so we are still working in a development environment so the setup is slightly different but as you imagine once you actually deploy this to the web your media folder or your static folder with your static files that potentially is going to be saved in the cloud somewhere maybe we start utilizing amazon cloud services and so on to kind of serve those type of images and those media types to your project somers rambling on but there we go so we've built a like feature with ajax inside of our blog and last point we will iterate the code so we'll look at this again we'll look at improving on it especially f expressions and once we have a look at that in a separate tutorial we then implement it within our blog
Info
Channel: Very Academy
Views: 3,556
Rating: undefined out of 5
Keywords: django tut, django tutorial, django 3, djangoproject, django examples, django ajax, learn django, django beginners, beginners django, django framework, django 2020, django like button, django ajax like button, django example, django with ajax, ajax and django
Id: Lsxc5ok4qdU
Channel Id: undefined
Length: 28min 46sec (1726 seconds)
Published: Sat Aug 15 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.