Learn the Basics of Django Signals

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
welcome to a new tutorial and this one we're going to be going through the basics and pretty much everything that you really need to know about Django signals now to get started all you need to do is just create yourself a blank project I've gone and done that for myself here I've called mine the DJ signals tutorial and that's all you really need so once you've got that open and you're ready to go in your editor then let's get started now I remember when I was getting started with Django I came across signals in my tutorials and I wasn't actually understanding it at all and I can't remember exactly why that was for some reason it just seemed a lot more complicated than it really was I kind of realized that the point of signals is actually really really simple and we've made it to be a lot more complicated than it actually is and to sum it up it really is what it says it is it's just a signal that something needs to take place in some other part of your application and I'm hoping in this tutorial to show you just how simple it is to use Django signals and some of the more popular use cases of where you can actually apply signals now basically a signal allows a sender to notify a receiver that an action was taking place so that's all that you really need to remember you have a sender and you have a receiver and it's basically the same thing as like react Redux actions and reducers it's the same kind of concept as that and so this is quite useful basically when you want to listen for specific events that you're interested in so for example if a user signs up on your website you want to record when that event takes place and when it does you want to perform some kind of action so an example of that would be maybe you have some kind of model that's related to your user which could be like a profile model and that model is specifically designed to have certain information stored on it but now when your user signs up they're not going to have to create a user and a profile themselves what you'll do is just let them create the user and then you'll listen for that event and then handle the creation of their profile based off of that signal and that's a very popular case of using Django signals and we're going to look at that in a second now what I want to do is actually just navigate into the browser and we're gonna go to the docks on Jango's website for signals and this is for the latest version of Django which is version 2.1 and basically what I want to show you is just how short this pages if I scroll down that's it that's all there is that Django is providing you on signals and there's a reason for that it's just a very simple concept and you don't want to over complicate this basically Django goes on to explain what a signal is and that's what we just talked about being a set of senders and receivers and then goes on to reference some of the built in signals that Django really provides you with and just as an example you've got the pre save and the post save signals and these are some of the more popular ones which we're also going to use basically pre save takes place before the save method is called on any model and the post save takes place right after the save method is called and so the post save would be used in the instance of creating a user's profile right after they've signed up and created their own user account but the main thing to take away here is the logic that's taking place it's sent before or after a models save method is called so the signal is the save me that that's what this means when the save method is executed then it's a signal to call some kind of receiver and the receiver will handle all that kind of logic which will create the profile link it to the user etc and there are a couple of other ones here I'm not going to go through all of them but it's the same kind of concept you've got pre delete post delete so this is basically taking place before after the models delete method or query sets delete method it's the same kind of concept it's basically just depending on what you actually want to listen for and what you want to do once that signal has been called and so let's go back into the project here and what I'm going to do is just open up a terminal and we're going to create ourselves an app that's actually just see if we're in the right directory so we're going to source and I'm just going to say Python manage our PI and we'll say start app and just let's say posts for example and then we'll go into our settings and scroll down and then just add posts to the app here to the installed apps there you go and we'll just create some models to work with so we'll just create a class call it post and to say model stuff model and then we'll just say title equals two models dot character field and we'll give it a max length say it equals 215 it really doesn't matter we're just creating a dummy model here and we'll say define the string of self and then return self dot title cool so that's our model so what we're going to do is just look at a couple examples of those signals particularly a good example is that post save and pre save so we'll just need those imports and if we check it over here it says it's from Django DB models dot signals dot pre save and then post save so let's go and import this here so say from Django DB models dot signals import and now you've got a couple here post to lead to post in it etc so we'll import post save and we'll import pre save and so now that's going to create our signals here to actually handle what is going to take place when the save method is executed on the post and we can refer back to the documentation here to see how this is done now to actually handle the receiving part of the signal we need to define a function so we'll just say define a save post now the arguments that go into this receiving function firstly is the sender now the sender is simply just the model that's actually signaling this to take place so in our case if we want a signal to take place when the save method is executed on the post model then the sender would be the post so we pass in the sender's the first argument secondly we pass in the instance and the instance is basically the instance of the model that's being passed in so again if the sender is the post then the instance is the actual post model object that we just created and we can actually then play around with that as well and then lastly we just add keyword arguments just to handle what else is passed in and we're not gonna do anything fancy let's just say print something here and that's it that's our receiver that's all we're doing when we actually execute the save method but now what we need to do is we need to link the receiver to the actual signal and the way that we do that is by using the signal that we just imported here so we just take for example let's use our post save so we'll say post save dot connect and connect is the method that you pass to attach the receiver you see it's this first argument here to the connect method first argument itself so you don't pass it in second one is receiver so we just pass in the function and we just create it that's the save post and then the next argument here is the sender and the sender is the post remember that's the model that's actually signaling this to take place so again we have the actual receiving function that's going to do something when the save method takes place and then you have the actual signal that is calling this to take place and all we're doing is referencing the receiving function to take place which is safe post and the actual sender that we're listening for if you didn't specify the sender it's an optional argument if you didn't specify this then it would take place after every single model is saved so in our case we don't want to do that we want to listen specifically for when the post model was saved so let's go and firstly make migrations to this so we'll say Python manage type I make migrations and then we can just take migrate and now I'm going to go into the shell and we're going to see what happens when we execute the save command so we'll say it from posts top models import post and it will just say that P equals to post dot objects create and then we just have to pass in a title and we'll say this is the first title and you can see something is returned to us now the reason for that is because when you call the dot create method this calls the save method as well it's creating an actual instance of the model and then saving it another way that we could do this is say let's say p2 and we'll say this is equal to a post now you can see that the something wasn't printed because the save me that hasn't been called yet so we could say P 2 dot title equals to second title and now we say P 2 dot save and now you can see something's being printed out so hopefully this illustrates the concept of what a signal is doing and obviously in this case this is just an example so we wouldn't just print something but we would do something here so so what you actually do here is really up to you I'm not going to provide any examples of what to do there because it really is just depending on exactly what you want to do but for example we could have another model and create that model upon creation of the post model but again that would just be going into business logic and not really focusing on the point of teaching how to work with signals so hopefully you understand that whatever goes in here is completely up to you and you can pretty much do whatever you want to do that's an example of the post save we can also play around and see what happens when we have pre save so if we say pre save connect again we pass in the same arguments we have the receiver and then sender so let's pass those two in there as well we'll save that and we can exit out of the shelving and run it again and we'll do the exact same things yeah we'll say from posts import post and then we'll say p3 equals 2 a post and I'll say p3 dot title equals 2/3 title and if we say p3 dot save now you get something and something now it may seem we're that both some things are being printed after the p3 save is called but basically what's happening is that this first something is being called at the beginning of the save method whereas the second one is being called at the end of the save method so that's that's actually what's happening it's to find another one and say define delete post or we could say after delete post or pass and sender instance and then keyword arguments and we'll just say print you deleted something and then what we'll do is we'll come over here to the top and we'll import another signal and this could be like post delete so basically taking place after that the lead method is called on a model and then we'll just say post delete connect pass in our after delete post as the receiver and then we say the sender equals to the post model as we've done before and then we can just get out of the shell here call us again and we just need to import our post model again and we'll just say that P equals to post objects dot first then if we take P this is one with the first title and if we say P dot delete now you can see you deleted something and then this extra line of output here but the main thing is this you deleted something which is what's being executed as a receiving end of the signal when our object is deleted so hopefully you can see how simple this is so far I'm just gonna exit out of the terminal here and we'll explore a few more signals as well so let's just bring them all down here the next one we'll look at is another one which you can actually find here on the documentation if we go down it's this request finished which is a pretty cool one because it's basically just listening for when a request is finished and then you can execute something and we also see that we can create a receiver in a slightly different way where we use a decorator and let's decorators specifically coming from Django dispatch which is quite cool as you will see now so basically what we'll do is we'll define as they do here a callback and again all they're doing is passing in the sender and then keyword arguments and then just decorating it with the receiver decorator and passing in the signal inside our decorator it's basically how we're reading nurses were saying this is a receiver this whole function is a receiver and we are listening for a certain signal which is the request finished so when the requests finish takes place then we execute this callback our receiver so let's do that right here what we'll do is we're going to our views the pie and we'll just say define home and we'll say that this just takes in a request and we'll just say return and what I'll do is just say from Django dot HTTP import the HTTP response and I'm just going to say return an HTTP response and in here we're just going to pass in here's the response just like that and then we can take this and bring it into our URLs so we'll just say from posts the views import the home view and then we'll just create a path here which goes to let's just leave it empty and then pass in home as the view like that and now let's run the server so we'll say - our pie run server and if we come in here go to the localhost we get here's the response and basically what we want to do now is just do something when this view is actually taking place and in our case we were looking at this request to finish the signal so let's take a look at that will import the request finished signal and we'll just bring it in here so from Django recorded signals import request finished and then the same kind of thing here we'll just actually copy everything right this the receiver and everything else so from Django dispatch import receiver then we use the receiver decorator and pass in the signal up specifically looking for which is the request finished and we just given it any name of my callback we could call this whatever we want so let's just call it post request receiver something like that and just print request finished as well and now let's go back here to the terminal and if we come back here execute this then now you can see request finished being printed out yeah in the terminal and that's basically doing exactly what it says does we listen for the request and the request is going through in our home view which we just set up and once the HTTP response is sent back that would be considered that the request is finished and then that activates our post request receiver which in turn prints the request finished and maybe you want to do some kind of logging maybe you want to keep track of the number of requests to a certain page and do some kind of analytics in your own project and maybe you could have some kind of model that keeps track of the count of each request then this kind of signal would basically just tally one on to that request count for the specific view that's just one example but obviously again you can do whatever you want to do here and now the question kind of arises for what happens if you want your signal to be completely unique maybe you want it to be like a button that's pressed or a friend requests are sent or an email anything so what about custom made signals well we come back here to the documentation you can see exactly how that's done if we just scroll down here you've got defining and sending signals and here's your applications can take advantage of this signal infrastructure and provide its own signals and that's quite cool so basically all you need is just the signal class where you define it and that comes from Django's dispatch which we've really seen here being imported and this signal class is the cost that all signals are already using so it's not something new that we're looking at this is just some more behind the scenes of how these signals actually work but basically all you need to do is just dispatch the signal and when you dispatch it all you need to do is provide an argument which in this case is the providing arguments and that as it says here is a list of the names of arguments that the signal will provide to the listeners so if we take a look here here they're using a pizza store as an example and one of the methods is send pizza which takes in toppings and size as its arguments and when you execute the same Pizza method on the class then it's using this Pizza done which is the signal the custom signal we've created here and it's saying dot send so that's a method that is available on a signal and the arguments are similar to what we've seen already it's the sender which is going to be the class that the method is on in this case a self dot class and then we have to pass in the arguments that are expected as stated here being the providing arguments here so you can see toppings and size so all you have to do is just say toppings which is the first argument equals to something and size which is the second argument equals to something else so let's take this what we just read here and implement this as an example so we'll just come down here and we already have Django Dispatch over here but what we'll also import is the signal then we'll just create some kind of signal here and give it a name so let's say this is the request counter signal and we just say signal and then we say providing arguments that could also be none but let's say that the providing arguments equal - some kind of timestamp and that's our signal so now all we need to do is call this signal whenever we want it to be called and all we do is just say dots in so here inside the request what we'll do is just come here and say dot send and all we have to do is just say that the time stamp equals two of course this isn't an actual time stamp but whatever we want is an argument for the sake of the tutorial so just add a date and we'll just bring our signal above here as well so that we don't get any errors and of course we also need to pass in the sender so we'll say sender equals two let's let's say this is the post model so we'll say from dart models import post and I'll just say that the sender is a post model just like that and now all we need to do is take our signal that we just created here and we could do the same kind of thing where we create a receiver and listen for when that actually takes place so we could just copy all of that there and we'll define this receiver and say instead of waiting for the request finished signal now we're going to use the request counter signal so we're using our own custom signal that we just created here and we'll define this as the post counter signal receiver we can add that there and it takes in sender and keyword arguments and then we'll say that this will print let's actually print the keyword arguments and let's see what that gives us yeah so we come here and refresh this and come back now you can see you've got this dictionary that's being printed out and you've got the signal which is the actual object stored in memory and then you've also got the timestamp and you can see that that's the timestamp that we entered here obviously this wouldn't be a static timestamp maybe you would dynamically generate this somehow but the point is that this is the argument that we passed in because it's a required argument and you can see it coming through here in our keyword arguments when we actually receive the signal and so and so that's really all there is to it we've covered pretty much everything that the Django documentation is mentioned about signals and that's really all there is so it's just understanding what a signal actually is and the concept of a receiver and how it listens for these events that we call and then we also got to see how we can create our own custom signal and even pass in providing arguments to it and then access those arguments as well with our own receivers as we've seen that close so I hope this video cleared up signals for you let us know what you thought of this tutorial leave a comment down below and otherwise thanks for watching don't forget to subscribe and we'll see you in the next one [Music]
Info
Channel: JustDjango
Views: 40,460
Rating: undefined out of 5
Keywords: django, django tutorial, python django, python, Django Web Framework (Software), Python, python programming, python 3, python 3.5, django python, python tutorial, how to python django, install django with virtualenv, django 2.0 tutorial, django signals, signals, django signals tutorial, django signals post_save, django signals example
Id: T6PyDm79PFo
Channel Id: undefined
Length: 22min 36sec (1356 seconds)
Published: Mon Jan 14 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.