Django: Getting Started Transcripts
Chapter: Users and Account Management
Lecture: Registering a user-created signal callback

Login or purchase this course to watch this video and the rest of the course contents.
0:00 So that's the profile, now to set up the signal for creation. The receiver decorator registers this function as a signal handler.
0:14 The post save value indicates the signal being listened for is the one that gets emitted after an object is saved.
0:22 The object I'm interested in getting this signal from is user. So I set that as the sender.
0:30 Signal handler functions take one required parameter and some optional ones. The required argument is a reference to the instance object that
0:38 emitted the signal. In our case that will be the user class.
0:43 This is necessary because you could have multiple senders registered with a single function. I'm only interested in creating a profile,
0:54 if the user object is newly created, the post save signal gets triggered on every single save. There is a key in the keyword
1:03 args called created that is true, if there is a newly created object. There's another edge case here as well.
1:11 When doing imports from fixtures, you don't want to create the profile automatically. The fixture is going to have that profile already,
1:20 Thankfully, the raw key word will indicate if this is being loaded from a fixture.
1:25 To recap, this code will only create a new profile if the post save signal was
1:30 for a user that was newly created and it wasn't created through loading a fixture.
1:35 The instance key in the key word dictionary contains the instance of the object whose creation caused the signal.
1:43 To make the code a little easier to read, I have stored that in a variable called user. This is the code to actually create the user.
1:58 There are other cases where profile might get created for you, like on the main form of the Django admin.
2:05 As such, line 22 does one last check to see if there is a reader in the database associated with the user.
2:12 If there isn't the get method on the query manager will raise a it does not exist exception, which is great, that's what you want.
2:20 Inside of the except clause the actual profile then gets created. If that user did exist, then the except clause won't fire and nothing will happen.


Talk Python's Mastodon Michael Kennedy's Mastodon