#100DaysOfWeb in Python Transcripts
Chapter: Days 53-56: Django part 2 - registration and login
Lecture: Update the Quote model to associate quotes with users

Login or purchase this course to watch this video and the rest of the course contents.
0:00 Great, now that we have login in place we can start working on adding the user to the quotes model so that we have quotes associated with the user
0:10 and then we can set up that only the user that is logged in can edit his or her own quotes. So let's cd into my quotes app.
0:21 Open models and import the User model which is provided by Django out of the box. Add this django.contrib.auth.models.
0:39 And then I need to make a ForeignKey relation to that user model and the way to do that is to say models.ForeignKey
0:54 specify the model that we link to, so user. And on delete we can do two things so if the user gets deleted do we want to cascade the deletes
1:04 so when the user gets deleted, delete all the quotes or do we want to put a no value into the quotes. On this case I'm going to choose the former
1:14 and that's specified as models cascade and I'm going to allow default of blank is true and no is true 'cause I already used some quotes in the database
1:31 which are not having the user associated. This makes it easier to have a migration without asking us questions or asking us for defaults.
1:40 Again the models cascade is to make sure that if the user gets deleted all the linked quotes get deleted as well. Then I'm updating the str method
1:51 to also put information in here who submitted the quote. And that's it. Now we need to make a migration because our model changed.
2:09 So I'm going to the outer terminal window and I'm going to type Python manage.py makemigrations And that made this migration.
2:25 And we see here that the field was added to the quote model. And it's a ForeignKey. Then we can migrate to actually commit it to the database.
2:39 And that relation now exists. Can even check that. And here under quote's quote we have a new field
2:59 user id of integer. Let's run the server. And nothing will happen yet. Other than that, this is still working and in the next video
3:17 we're going to update the views and templates to accommodate this change. Users will be associated with quotes and we'll make sure that users
3:27 can only edit their own quotes.

Talk Python's Mastodon Michael Kennedy's Mastodon