Creating a Custom User Model (Django)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
Django has a built-in user object as we've already seen but that user object isn't that useful in my opinion the best thing to do in almost every situation is to build a custom user model that way you can get it to fit the exact needs of your particular project one of the biggest issues I have with the built in user model is that it uses the user name as the login parameter I think that the email is much more practical unfortunately the Django newbies out there which I'm assuming most of you are creating a custom user model isn't outlined very well in the Django Doc's so follow along very carefully because I think it's very easy to get mixed up here and if you're curious I'm looking at the documentation where it shows you how to create a custom user model you can follow along with this if you want to but I'm going to be showing you everything you need to know in this video so the first thing I want to do is I want to actually go into our project directory and I want to delete this database I want to delete the database because I want to start with a completely kind of clean slate because right now we have users registered we have stuff in the database that isn't going to be there later on so just delete the database and we're also going to delete the migration so I'm deleting I'm highlighting all of these migrations including the initial one I'm going to right click here and go to delete file so the only thing left make sure you still have the migrations folder you still have the anit pi file inside the migrations but all the actual migrations themselves have been deleted so basically now we we have a completely kind of clean slate and I can I can activate my virtual environment make sure that's activated and then I want to run the server just to regenerate that database file so there's that SQLite database file being regenerated now I can stop the server and we can work on what we were going to start building in this video which is a custom user model so how do we go about building a custom user model well we need to actually create a new app first of all this is going to be the account app so I'm going to go Python manage py start app account and the account app is going to contain a model for our custom users it's actually going to be called account but it's technically a custom user so I'm creating that app and now since I've created a new app I should see that over here which there it is right there and as you know as we've talked about before whenever you create a new app in Django you need to go into the settings file and you need to add that app right here if you don't do that it won't work properly and you'll get errors on your server so once I've added that I'm pressing ctrl s to save that and now I'm going to minimize this I'm going to close this I go into account go into models and we're going to build our new custom user model before I start building I'm gonna get a couple imports that we're going to be using so from Django dot contrib dot dot auth models I want to import two classes abstract base user and base user base user manager those are two imports that we're gonna need for this video I just wanted to add them ahead of time that way I don't have to just kind of add them I don't want to break the flow as I'm writing out these classes if you're curious what abstract base user is and base user manager once again check out the documentation it talks about that there's this abstract user class and then if you scroll down more there should be abstract base user but yeah if you want more information on these you shouldn't you should read this but basically it's just these are classes that you could use to extend the kind of generic Django user model and create a custom user model so check out the docs if you want to learn more but I'm gonna show you everything you need to know in this video all right so let's create a new class this class is going to be called account and it's going to extend the abstract base user class I think in Python you or I think in Django and Python you call them classes I'm not exactly sure because I'm an Android guy but I'm gonna call them classes I think it sounds right so whatever so the first field is I want to use an email I want to have an email parameter and this is what we're going to be using to log in so I'm going to do models dot male field I'm gonna go over both name and set the verbose name equal to equal to email I also need a max length parameter so max length equals 60 characters and I want of course it to be unique since this is going to be the unique identifier for anybody who creates an account they're going to be able to login using their email instead of using their username which is the sort of generic the base django functionality so now I'm going to create a username field because I still I still actually want a username field I just don't want people to be able to log in with our username so max length equals let's just do 30 characters and of course this one will also be unique so people can have the same username now the fields that I'm gonna add now are actually required for the abstract base user class and like I said you can check out the documentation if you want but just know that if you if you go to create your own website kind of lost money oh my my keyboard dad there there we go if you go to create your own custom user model you will need to add these fields so just keep that in mind actually you know what I'm gonna actually just copy this from the source code because there's no point in me typing this out so I'm going to the github page for this project going to the coding with Mitch blog course I'm gonna go to let's see this branch is creating a custom creating a custom user model going to source going to account going into models and you could technically copy this entire file if you wanted to but or I recommend following along with me it's it's better to learn so all I'm gonna do is I'm going to copy these fields right here go back to the project and I'm going to paste those in also just as kind of a side note for those of you who aren't familiar with Python notice that all of the spacing so the whitespace is all the same here if I actually used a space here instead of a tab you'd see these little white dots and this would actually cause an error and sometimes they can give kind of cryptic errors so I just wanted to let you know that if you ever get kind of a weird error make sure to highlight everything and make sure that the spacing is correct so what you want to do is just do you want to tab it in so that all the spacing matches so anyway let's let's take a look at these fields so we have date joined last login is admin is active is staff in a super user so all of these fields are required if you're going to create a custom user model these ones are actually required and then of course I could add any more if I wanted to like I could add you know first name you do a character field I could add you know date of birth anything but the the point that I want to make here is that these are required so if you go to build a custom user model you must use these fields also pay attention to the default values that I gave to these billions so is admin the default value is false is active set to true so every user is just active by default is staff and his super user of course are set to false because you don't want to give extra permissions to anybody who isn't supposed to have them next comes another very important kind of property - or I guess thing that you need to know when you're creating a custom user model you need to set the username field to whatever you want the user to be able to login with now this is something that actually bothers me because it's really not intuitive with Django but basically what it's what it's saying here is whatever you want to be able to log in use this so it's I think this is a stupid name it should be like login field or something like that but it's user name field it's a keyword so you have to set user name field equal to the to whatever you want them to login with if it was user name you would put user name but in this app obviously like I said we want to login with the email so I'm setting email next I want to set anything that is required so any fields that are required when they're actually registering so you can do a list here or a Django dictionary the only field that I want them to be able that I'm requiring other than this of course is the user name field so when they register I want them to they must have a username and they must have an email and they must be unique if I was to create a another field like first name just as an example I would do models character field ooh like max length equals I don't know 30 if I had this first name field and I wanted them to and I wanted them to include a first name when they register I would do first name like that then it would not allow them to register unless they entered their first name but of course in this I don't really care I don't I don't want a first name I'll just comment that out just in case you want to look for a reference okay now we have to kind of just do some of the Python stuff we need a Stringfield so this is like a two-string method remember in android basically what this means is whenever I print an account object to a template what do I want to display well I want to display the email you can choose anything of course you could choose the username if you want it to just replace that with username or you could even concatenate the two you could do like you know comma self username and that would print out the email comma the username whatever you want I'm just gonna use the email so next now let's we need to define a couple of functions these functions are required if you want to build a custom user so you need you need to use these no matter what basically there's there's one that gets the permissions for this particular this particular user and don't worry about this if you don't if you're confused just literally copy this because it's it's really not going to affect you unless you have an a website that is quite high-end where different users have different permissions you have staff you have admin you have users all that kind of stuff so just kind of copy this out and move on I think is is the advice that I would give you the next one is has module permissions self app label and I just want to return true so I'm just returning true for this no matter what it will always have module permissions does the user have permission they have permission if they're admin so they can basically do stuff if their admin is what I'm saying so that's why here the admin parameter is set to default equal to false so that if because if a user is admin they're going to be able to change things in the database so that's that should be the only sort of functions that we need to create a custom user model now the next step is creating something called a custom user manager and if you look at the Django documentation as I said you can read through here and it will if you scroll down you'll find somewhere where it says we recommend writing a manager for a custom user model so that's what I'm going to show you to do once again I'm going to show you how to do everything so don't worry about it if you don't want to read the docs I'm going to show you everything you need to so I'm gonna create another new class for and it's going to be called my count manager it's going to extend that base user manager that I imported up top there and let's see it says if you do read the docs I just want to kind of mention it says that if you create a custom manager you need to override these two methods create user and create super user so basically what I'm doing is I'm defining what I want to happen when a new user is created and when a new super user is created so define create user is the name of this one self it takes email it requires a username and it needs a password so so so I'm passing an email and username here because those are the two required fields to create a user I must have an email since I'm logging in with an email and username is a required field if you had any other required fields like if you know this was here and you had your you know first-name and you were requiring that you would also need to add a first name parameter to here just kind of as an FYI in case you want to require more information when you register users so there's our there's our fields that are required to create a user so now what are we going to do with this well first of all if not email that I want to raise an error so I want to raise something called a value error users must have an email address so just raising an error if for some reason the user did not enter their email if not user name then I want to do something similar and just say they must have a user name users must have a user name all right so what if they actually do have a user name they do have an email then what well then I want to do I want to create that user so we're going to go user dot model and inside model I want to pass the parameters that they require so email equals self dot normalize email and don't be confused by that normalized email all that does is it will convert all of the characters in the email to lowercase so you're you're normalizing it for when it gets inserted into the database and then of course you're just adding that username normalized email it usually isn't available you can't just use it anywhere it's available inside of the base user management class so that's why I'm able to access it here if you were in a view you can't just call normalize email it's because it's inside this base user manager class that I can I can use it so now I want to do user dot set password same thing with set password by the way it's a method that can be used on a user object I want to set it to the password and then user dot save using equals self dot DB underscore DB and then return user and that is gonna be our create user method I'm kind of losing my voice here what's going on again I just want to say don't worry about the notation here just copy kind of the flow of what I'm what I'm using if you had an another extra required field like I said you'd add it here you check for it and then you'd add it to this model method you'd still set the password and still save the same way so everything else would work the exact same way next I want to create a super user so create super user this is going to be very similar we need self email username and password we need to do kind of very similar process right here so user equals all this stuff except I do want to add a password field here now now we need to set some more properties so is admin is active is staff is super user all of these defaults will get used when they create a user but we don't want those defaults to be used when creating a super user because we want them to be an admin obviously so is admin equals to true I'll need a bunch of these so all four of these actually I don't need four just need three but is staff equal to true and is super user equal to true so all of those properties where the defaults are set down here we're changing them because it's a super user obviously we want them to be able to do anything so user dot save once again using using equals self dot DB and then I want to return the user that's it so we have our custom user manager we have our custom user object and now I want to I want to tell this there's a TARDIS account object where to where the where the manager is so how to use the manager you do that by say setting an object's parameter so objects equals my account manager and just reference the account manager that we built up here so if i zoom out there is our our model so we have our account our custom user model and we have our custom Account Manager which is the custom user manager so the last step in this whole process is we need to go into my site go into settings and I need to set a property this property is called the auth user auth user model and then I want to set that to the model that I just created so that'll be a count which is the app I'm referencing the account app and I'm just referencing the account model so I'm referencing this right here what this does is it overrides the default behavior that's built in with Django for a default user object and I'm saying instead I'm authentic ating users using this custom one that I just built so I need to tell Django where my custom user model is basically now we're ready to go to our server so python managed up pete why i already created a new database so i need to do make migrations to migrate our new model there's the migrations python manage that py migrate to commit all those changes now python managed up py and run server and now let's go to our server and let's take a look so if i go to the admin and all i need to create a super user actually so cancel that python manage py create super user know so now this is going to use that create super user method that we just built so that's going to run this method right here so i need to enter the email mitch at a beauty a username will be mitch my password is just password password yes override that and now let's run the server go to the admin again and i'm going to log in with my password of password looks like that didn't work just spent a couple minutes debugging I found a couple mistakes so inside of the model here this should be using instead of user for the save method that one's using that's good and all so what else did I need to change this needs to be create user instead of model so inside create super user we call self create user then inside create user we call self dot model now I'm going to press ctrl s to save that and we need to kind of restart this whole process so I'm going to make sure the server is not running I'm going to delete the SQLite database I'm going to also delete the migrations inside of account so it looks like there's just that one I'm deleting it that should be good so now I'm going to go back to our server Python managed up py make migrations Python manage dot py migrate now I want to create that super user so python mashup py create super user let me Mitch at Tavian GA my user name is Mitch my password is password yes there we go and now python managed up py run server and now let's see if it all works so going to the admin type my password of password there I am logged in and oh I didn't add the account to the admin so the question stuff should actually be removed also so going back to sublime text and going into the admin here I want to call from account models import account and then admin dot sight register and register the account and I'm going to save that I don't need to restart the server with admin stuff it kind of autumn oh it looks like there's a problem let's check out the console could not import cannot import from account models import all the scenes the capital import account there we go so the server doesn't need to be restarted admin stuff doesn't need a server restart going to accounts and there should be that one super user right there which is Mitch at Tavian CA now I want to test this I'm going to create a another user looks like obviously we have some work to do here so I'm going to give this user a password of one to three password one two three four this will be Jessica at gmail.com her username will be Jess if she had been no is she active yes staff no superuser no let's click Save and continue that user was created if I go to accounts there's that secondary user that's now created so there's a there's obviously a couple of things wrong with this picture number one is I shouldn't be able to see what password what the password is and I shouldn't be able to change the password from the admin this is technically a hash so or usually what you can do is you can hash these passwords so that they don't actually show in the admin it just shows an encrypted version of it so we still need to be able to we still need to fix that in the account screen I want to see more attributes listed so if I go to the account screen all that I can see is the email it would be nice to show the email the user name the date that they joined you know some of the other fields that we have in the model which are available here but currently there's just that single one so we're gonna work on editing that two and four and number three is I also can't search users there's no way to search users here so if I had like a thousand users ten thousand users a hundred thousand users it'd be almost impossible for me to find them and that's obviously a problem because sometimes you got to change things manually inside of an account like if a user has a membership they want to change the membership and there's a problem whatever it is you need to be able to find these users manually so in the next video we're going to work on all the things that I just mentioned basically that means just working on the admin console hiding these passwords getting some more details in these in these rows and also being able to search users you
Info
Channel: CodingWithMitch
Views: 79,356
Rating: undefined out of 5
Keywords: abstractbaseuser, django custom user, custom user django, django email login, django email authentication, email authentication django, custom user model django, custom user model django 2, how to make a custom user model with django, django user authentication
Id: eCeRC7E8Z7Y
Channel Id: undefined
Length: 21min 57sec (1317 seconds)
Published: Wed Jun 19 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.