{"id":112,"date":"2024-02-17T05:00:43","date_gmt":"2024-02-17T05:00:43","guid":{"rendered":"https:\/\/mrcoder701.com\/?p=112"},"modified":"2024-03-15T16:56:51","modified_gmt":"2024-03-15T11:26:51","slug":"custom-user-in-django","status":"publish","type":"post","link":"https:\/\/www.mrcoder701.com\/2024\/02\/17\/custom-user-in-django\/","title":{"rendered":"Custom User in Django"},"content":{"rendered":"
Custom User Model in Django <\/p> This post explains step-by-step how to create a custom User model<\/a> in Django.<\/p> By the end of this article, you should be able to:<\/p> Django documentation<\/a> says that AbstractUser<\/strong> provides the full implementation of the default User<\/strong> as an abstract model, which means you will get the complete fields which come with User<\/strong> model plus the fields that you define.<\/p> Example<\/strong><\/p> In the above example, you will get all the fields of the User<\/strong> model plus the fields we defined here which are address<\/strong> and birth_date<\/strong><\/p> AbstractBaseUser<\/strong> has the authentication functionality only , it has no actual fields, you will supply the fields to use when you subclass.<\/p> You also have to tell it what field will represents the username, the fields that are required, and how those users will be managed.<\/p> Lets say you want to use email<\/strong> in your authentication , Django normally uses username<\/strong> in authentication, so how do you change it to use email<\/strong> ?<\/p> USERNAME_FIELD<\/strong> is a string describing the name of the field on the user model that is used as the unique identifier.<\/p> In the above example, the field email<\/strong> is used as the identifying field.<\/p> It is important to note that you can also set email<\/strong> as your unique identifier by using AbstractUser<\/strong>, this can be done by setting Start by creating a new Django project along with a users app:<\/p> $ mkdir custom-user-model && cd custom-user-model Feel free to swap out virtualenv and Pip for <\/em>Poetry<\/em><\/a> or <\/em>Pipenv<\/em><\/a>. For more, review <\/em>Modern Python Environments<\/em><\/a>.<\/em><\/p><\/blockquote> DO NOT apply the migrations. Remember: You must create the custom User model before<\/em> you apply your first migration.<\/p> Add the new app to the 2)<\/strong> second comment in urls file path(\u2018admin\/\u2019, admin.site.urls)<\/p> <\/p> <\/p> 3)<\/strong> open account folder and open file Models.py<\/p> Add the following line to the settings.py<\/em> file so that Django knows to use the new User class:<\/p> Now, you can create and apply the migrations, which will create a new database that uses the custom User model.<\/p> (env)$ python manage.py makemigrations Then now uncomment the second uncomment in urls file path(\u2018admin\/\u2019, admin.site.urls)<\/strong><\/p> * create a superuser.(env)$<\/p> python manage.py createsuperuserEmail address: test@test.com *then later open \/account\/admin.py register user model<\/p> In this post, we looked at how to create a custom User model<\/p> You can find the final code for both options, Let\u2019s Get in Touch! Follow me on:<\/p> >Instagram: @rajput_gajanan_07<\/a>.<\/p> >GitHub: @gajanan0707<\/a><\/p> >Linkedin: Gajanan Rajput<\/a><\/p><\/figure>
Objectives<\/h1>
AbstractUser<\/code> and
AbstractBaseUser<\/code><\/li>\n\n
AbstractUser vs AbstractBaseUser<\/h1>
from django.db import models\nfrom django.contrib.auth.models import AbstractUser\n\nclass MyUser(AbstractUser):\n address = models.CharField(max_length=30, blank=True)\n birth_date = models.DateField()<\/code><\/pre>
Example<\/strong><\/h1>
from django.db import models\nfrom django.contrib.auth.models import AbstractBaseUser\n\nclass MyUser(AbstractBaseUser):\n email = models.EmailField(\n verbose_name='email address',\n max_length=255,\n unique=True,\n )\n date_of_birth = models.DateField()\n is_active = models.BooleanField(default=True)\n is_admin = models.BooleanField(default=False)\n objects = MyUserManager()\n USERNAME_FIELD = 'email'\n REQUIRED_FIELDS = ['date_of_birth']<\/code><\/pre>
username = None <\/code>and
USERNAME_FIELD = 'email'<\/code><\/strong><\/p>
Project Setup<\/h1>
$ python3 -m venv env
$ source env\/bin\/activate(env)$ pip install Django==3.2.2
(env)$ django-admin startproject customeUsesr.
(env)$ python manage.py startapp account<\/p>INSTALLED_APPS<\/code> list in settings.py<\/em>:<\/p>
1)<\/strong> first comment in installed_apps this line 'django.contrib.admin',<\/strong><\/code><\/p>
INSTALLED_APPS = [\n#'django.contrib.admin',\n'django.contrib.auth',\n'django.contrib.contenttypes',\n'django.contrib.sessions',\n'django.contrib.messages',\n'django.contrib.staticfiles',\n'account',\n]<\/code><\/pre>
from django.contrib import admin\nfrom django.urls import path\n\nurlpatterns = [\n #path('admin\/', admin.site.urls),\n]<\/code><\/pre>
from django.db import models\nfrom django.contrib.auth.models import AbstractUser\nfrom django.utils.translation import ugettext_lazy as _\n\n# Create your models here.\nclass User(AbstractUser):\n username = models.CharField(max_length=30, unique=True)\n email = models.EmailField(_('email address'), max_length=254,unique=True, null=True, blank=True)\n avtar = models.ImageField(upload_to='thumbpath', blank=True)\n mobile_no = models.CharField(max_lenght=15)\n class Meta(AbstractUser.Meta):\n swappable = 'AUTH_USER_MODEL'<\/code><\/pre>
Settings<\/h1>
AUTH_USER_MODEL = 'account.User'\nswappable = 'AUTH_USER_MODEL'<\/code><\/pre>
(env)$ python manage.py migrate<\/p>INSTALLED_APPS<\/code> list in settings.py
<\/em>Uncomment in installed_apps this line'django.contrib.admin',<\/code>INSTALLED_APPS <\/p>
INSTALLED_APPS = [\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'account',\n]<\/code><\/pre>
from django.contrib import admin\nfrom django.urls import path\nurlpatterns = [\n path('admin\/', admin.site.urls),\n]<\/code><\/pre>
Password:
Password (again):
Superuser created successfully.<\/p>from django.contrib import admin\nfrom .models import User, UserProfile\n# Register your models here.\nadmin.site.register(User)<\/code><\/pre>
<\/figure>
<\/figure>
Conclusion<\/h1>
AbstractUser<\/code> and
AbstractBaseUser<\/code>, in the django-custom-user-model<\/a> repo.<\/p>