Python Django - How to add custom fields to the User Model ?

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everyone i hope all of you are doing well in this video i will show you how to extend the built-in user module in django now if you want to become a better django developer to find a back-end python developer job then i think that the playlist that i'm going to prepare now which i will name django for everyone is exactly for you because i will prepare a lot of django tutorials that are rarely covered in most of the crash courses or in any django beginners tutorial and i think those videos will help you to prepare better portfolio projects and as well as just becoming a better django developer so this video will be the first one among all the videos that i will prepare in the future which will cover how to extend the built-in user model so if you don't want to miss any video in this django for everyone playlist then definitely consider subscribing to my channel and let's get started [Music] now throughout this series of django videos i'm going to use a basic project that i have came up with and that will be inside the django for everyone repository and you can see that we have here a base app directory so that will be the directory that we are going to work on when i will be showing you some of the things that i will explain through how to different tutorials now i'm not sure if you have a django project of your own but if you have then you might decide that you like to do your own reverse engineering throughout my explanations but maybe you would like to work with this basic project that i have made for you so it will be as easy as using a git clone command and then you can basically copy the repository url by clicking here and press right there and then you can just paste this in with right clicking on your cmd and that will be it and now you have cloned repository and you can work with it now if you don't have git installed then i highly recommend you to install it and work with git command line utilities but if you want to skip that then you can also download it as a zip file and extract it wherever you want all right so let me go inside django for everyone here and as well as use a cd base app and now i will clean the screen and i will show you what is going on here so you can see that we have a basic project inside this base app directory so let's just go ahead and open this directory with pycharm alright so i have opened my pycharm and you can see that now i'm about to execute python manage.py run server just to really show you for a few seconds how this application looks like right now so let me bring in the browser and you can see that when i go to localhost port 8000 then it automatically takes me to a basic home page now if i maximize this then you can see that it has a nice navigation bar with some title and also a secondary title and you can see that there is not too much complex things going on here so that will be a perfect basic application that i want to show you throughout this django series okay so here is the project that i'm going to work on now one of the first things that i want to do here would be to create a new django application for our extended user module so we will have an organized application of django that we can work with so i'm just going to go to our terminal here and use a create app command in order to create a new django application so let me clean the screen here and just say django dash admin start app and then we will name this account now the reason that i'm doing this it is because we probably like to have an organized application with all the users and we don't just want to pick a random location to add more fields to already existing user model now before we get into programming this then i want to explain main difference between extending the user model to creating your own user model with its own fields defined from scratch so when we talk about extending basically we grab the existing attributes like username email and the password and then we just add more fields in order to extend the attributes of the already existing user model now to be honest with you the best practice when you start a project with django would be to create your own user module before you even go ahead and fill in data in your database but we might have situations where the user model for us could be enough but we'd only like to add some more attributes like maybe birthday or gender or stuff like that so that will be what i'm going to show in this video i'm not going to cover how to create the user model from scratch but we will just extend the existing user model in the most smooth way as we can so let's dive into it so i'm going to go inside the account application that we have created and then i'm going to use the models.py file in order to create a new model that we could name it account now we have to somehow connect this model with the built-in user model so let's see how we are going to do that all right so the first step will be to create a new module that we could name it for instance account so let's go ahead and do that so i'm going to go here and i'm going to use class account and then i'm going to obviously import from modules dot module and then i'm going to say in the very first field something like the following so i'm going to use a user field and that will be equal to modules dot one two one field now one two one field is essentially the same as a foreign key that you might have heard of and it is just a way to carry connection between one specific user object to one specific account object so that is why we have to have this one-to-one relationship between an account object to a user object so now we're gonna need to pass in here several arguments and the first one is going to be the built-in user model but we cannot do this directly like that because we need to import this module somehow so it will be by from django dot contrib dot a u t h auth dot modules import user like that and that will be the built-in user model that currently your django application uses all right so now that we have done this then we're gonna need to define some more important actions in here now what will happen for example if we were to delete one of the user instances so we need to somehow tell this account object that is associated with the user object to delete the account as well so that is why in most of the cases that you use a one-to-one field you need to also pass in what this will do on delete and we want to pass in here modules dot cascade like that so we could have the option to also delete the account object when we go ahead and delete the user object from some location like the admin panel all right so now that we have designed this then here is the exact location that we can decide for random fields that we would like to add to our user module so i think that feels like birthday or gender could be great candidates for some additional fields in your users so let's say that birthday is going to be equal to models dot date time field and let's instantiate that and then we can go ahead and say modules dot chart field and then we can pass in here max length is equal to 6 as we are going to have two options for male and female so let's see how this could be done actually let's see how we can have choices for some char fields so i'm going to use here choices as in argument and then this one needs to receive a list of tuples so let's say that we will have two options so that will be the proper way to pass that now in the tuple we are going to include the following values in order to have them as choices so the first one will be the way that the value should be represented in the drop down when we try to basically create an account object from the admin panel so we want to display their mail and we'd also like to decide as the second argument here what will be the value once this choice will be selected so since we want to keep them kind of similar then i will also use here mail as well so now in our second tuple i will do the same for female and let's just type this one more time and that will be the way to use a char field that will have multiple choices so that's actually a great way to define this because it is a great idea to have the choices as a drop down even when you want to decide the gender from a drop down when you want to come up with a template of your own alright so now that we have this then let's go ahead and also overwrite the double underscore str method so we will have a nicer way to see the object itself so let's return here something like self dot user but username now the reason that i can do this although i see a warning it is because each of our account objects are going to be associated with a user object as well so that's why if we will have an associated user object then we will always have the username attribute so that's fine that we see a warning that this attribute might not exist all right so now that we have this then let's go to our terminal and submit our changes now our application is currently down so before we take this up then let's go and use python manage dot py make migrations now i'm not gonna lie i forgot to do something before i run this command and that will be to include this application in our settings file so let me do this quickly so i'm going to go to our base app and settings now i'm not sure if you're aware of this but there's actually an installed apps list as a configuration in your settings settings.py file that should be looking like the following now you also want to include here the new application that we have just created by only saying here something like the following so it will be account dot apps dot account config like that and then we should also pass in here comma to not screw up the list and now that we have this and we saved our changes then the entire jingle platform will recognize our account application and then we are allowed to make migrations because it will recognize them so now let's go back to our terminal and run it and then you can see that we have a migration about create model account so now that we have this then we are allowed to say python manage dot py migrate and that will mean that now our sql library file will have a new table with a name of account and that is perfect all right so currently i'm working on my admin.py file inside the account application and here you might have expect to only see something like admin dot site dot register as you're probably aware of that in some basic applications that you want to register your model now doing this for the account model is not a best practice because then for every time that we create a user then we're gonna also go to that account admin page and add an object right there so in order to avoid this we can actually use special methods to basically add the account fields as additional fields to the already existing user admin panel so in order to show that let me quickly take you to the admin panel where we can see the built-in users so let me actually run here the server and excuse me for that this will be manage dot phi run server and then oh excuse me we should have delete this so let me do that and open our terminal again and now our application is running so let me quickly bring here the website now we can see that we need to log into our admin panel to actually show you this so let's create a quick super user here now a super user if you know or not will be the user that will have all the privileges to take different actions in your application so in order to create that then we need to clean the screen first and then say python manage dot py create super user like that and then let's actually use a random user here because the changes that i will do here will also apply to you if you will use this application by the end of the tutorial from my github repository so let's use a generic user here like admin and then let's just throw in a random email address and then the password will be a capitalized a lowercase and then six five four three two one now the reason that i'm telling you the password because you might want to explore things by yourself by the end of the tutorial so i want to make sure that you will have the access for the admin user in here so now that i have created this password then let's go ahead and see what will happen now if i was to access to the admin page so i will use a run server now and then i will go here and i will log in with my super user so i think i mismatched the password so it should be something like that all right so in the users you can see that now we have one user now the thing that i wanted to show you is that you have the option to go to your user panel page in here and actually customize it a little bit to add the additional fields that you want to add from the account model so that's exactly what we are going to do in this stage we are going to edit this user panel of the django and we're going to need to add our custom fields so now let's go ahead and do that so i'm going to go here and first of first i'm going to delete this comment from here and i'm going to need to use some imports so the first one will be from account dot modules import account because we probably want to use our own model of account here and we are also going to use the built-in user model so i will say here django contrib dot auth dot modules import user and this should be enough for now all right so in order to add something that is additional to already existing register module like the user model that we have seen previously we gonna need to use specific classes to achieve such a task now in order to do this django documentations recommend to create your own class that will inherit from some class that is called stacked inline so in order to start with that then i'm going to say something like the following so it will be class account in line and let me actually use inline like that and this will inherit from admin dot stacked in line and that was the class that i was talking about that django documentation recommends to inherit from in order to basically have your own specific fields for already registered user model all right so now that we have this then by convention we need to specify several arguments that are kind of required because we inherit from this existing class now this django class here has some constants that it expects from us to override them and one of them should be the model that we want to display in additional to the user model so it's going to be equal to model and you can see the auto completion because it comes from this parent class in here so the model is going to be equal to account and we also going to pass in something like the following so we are going to pass here can underscore delete is equal to false now the reason that i want to do this because i want to avoid deleting accounts if the user is not deleted because the account must be associated with the user and we should not delete accounts without deleting a user so that's why i'm passing here something like the following and the last thing that i will pass here will be also one more convention constant that looks like verbose name plural and that is going to be equal to accounts now that is useful because you have control of how to display the objects when the admin displays them in plural ways so that's why i overrided this as well and now that we have finished with this entire class then we need to somehow re-register the existing user admin panel so it will be by saying admin dot site dot unregister intentionally and i will unregister the user module and then i will duplicate this line with ctrl d and let's actually try this one more time all right and then i will register this user admin panel back but we need to pass in here some additional arguments in order to register our own configurations as well so there's actually one more convention that we should follow according to django's documentations so that will be by including this account inline as an inline panel that should be added to the user admin panel so doing this might require from us to create one more additional class that we should follow specific conventions so according to django documentations we should use a new class that inherits from a class that is called user admin and that is the class that is responsible to visualize everything that you have seen previously in the user admin panel so it is going to look like class and we will name our class in some way so let's use just an underscore and then we gonna need to inherit from user admin now you might ask yourself how we are going to access this user admin so that is going to use one more import and it is going to look like from django dot contrib dot auth dot admin and we should import the user admin like that and now that we have done this then we're gonna need to overwrite the inlines constant inside this user admin parent class so it is going to look like in lines and that will receive a tuple and now inside this in lines we are allowed to pass our account in line that we have customized so now we will say account inline and in order to recognize this whole expression as a tuple we're gonna need to pass in here a comma and we are good to go all right so now that we have done this then let's go ahead and give this class a name so let's call it something like custom customized user admin something like that and then let's go ahead and include here in the register the customized user admin as well so that will be responsible to take our account in line and add it as an additional fields in the admin panel so in order to test this up then i'm going to check first if our server is up and running and let's actually see if it's okay by cleaning the screen and use a run server so you can see that now our server is up and running and if we scroll up in the django administration and go to users and let's actually see the admin user and down here you can see that we have the option now to include birthday and gender so that will be one way to extend the fields of the built-in user model so now you can use a date to describe your birthday in here and i know that i included here date time field and not date field so it is probably a better idea to have it as a date field so excuse me for not paying attention to that in the first place and let's just do it very quickly because in birthdays you probably don't look to specify the exact time so if we open our project and go to modules then let me change this to date field so it is more accurate all right so now that we have changed this then let's exit our application for a minute and use python manage.py make migrations and as well as use python manage.py migrate and now let's run our application and see if the changes are great so if we open our admin panel again and refresh this page then you can see that now we only got this date option in here so let's use a random date like today and use female and save our changes and you can see that now we have the changes being saved now you might also want to see the account information in a separated page and you may not want to dive into the user specifically so in order to do that you can also register the account module separately so i'm going to do that just to show you so i'm going to open the pycharm and just down here i'm also going to use an admin.site.register method to basically show you that the account object is really created so now let's go back to our admin panel and refresh this page and you can see that we receive accounts and you can see that we have this admin and you can see that the information here is quite equivalent now in order to test this out with creating a new user then let's see what will happen if we were to try to create a new user from this admin panel here and pay attention that we want to create a user object and not an account object the accounts are just additional fields to the user object so i'm going to use add in here and you can see that also here we have the account panel that we should feel so let's use a secondary user like user 2 and the password is going to be same like before so a capitalized a lower case and then 6 to 1 and i'm going to do the same for password confirmation and now i can also specify a date here as birthday date so let's pick a random date like 9th april 2020 and let's use female again and save our changes so now you can see that everything pretty much working in here and you can see that for each user object we have an account object that is associated now if we one day like to delete users then we should expect to see the account object that is associated to being deleted as well so let's test this up so i'm going to now delete the user tool by scrolling down here and using delete now you can see that in summary we have some more objects that are going to be deleted and you can see that it says to us that the account of user 2 is also going to be deleted so that's perfect that's what modules.cascade is responsible for so now that we have done this then you can see that the user is deleted and as well as the associated account so that is a one way to extend your user model again there are multiple ways to achieve such a task but using one-to-one field is actually a wonderful idea to add some more fields to the built-in user model okay so this will close out the episode if you have any specific ideas that you feel not enough comfortable with django then let me write this in the comment section so i can really make a tutorial on that specific topic now just for your information there are always room for improvement when you want to make your application robust enough so if you want to always force your users to fill in birthday and gender as well in your customized template then you can also use something that is called django signals which is a bit complex topic and can lead to a confusion when you work with them because it is just like events that are listening to changes in your database and performing some additional changes in addition to what has been changed so you can use also django signal rule that will go ahead and say for every time that you create a user object create an account object as well because if you are going to create a user object now let's say from your customized template then you don't have anything that is going to force to create an account object that is associated with it as well so that is just a side point that i wanted to mention and that will be it so again if you enjoyed in this video please make sure to hit the like button and as well as subscribing to my channel and i will see you very soon
Info
Channel: JimShapedCoding
Views: 2,180
Rating: undefined out of 5
Keywords: Django, Django user model, Django Python, Python Django, python back end project, python django portfolio, Django Extend the user model, Django custom user model, python website development, Django for everyone
Id: kRJpQxi2jIo
Channel Id: undefined
Length: 26min 10sec (1570 seconds)
Published: Sun Jun 27 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.