DEV Community

Raj Sahu
Raj Sahu

Posted on

Django Custom user model

In django we can create Custom user Model using AbstractBas

eUser. If, however, we wan't to use an email address instead of a username as the user identifier, you have to extend AbstractBaseUser.

Requirements:-

we know Python and Django frameworks.

we used Django 3.9 and python 3

Getting started:-

First, we create a folder called User and then install virtual environments using pip3 install virtualenv

we create a virtual environment using virtualenv venv and then install Django in virtual environment

Now we create a Django project using django-admin startproject Pro and then we create a app inside Project called Pro using python3 manage.py stratapp app

We install our app inside project folder in settings.py in INSTALLED_APPS

Now we create models inside app in models.py file first we import AbstractBaseUser and BaseUserManger from django.contrib.auth.models, from django.contrib.auth.models import AbstractBaseUser, BaseUserManger

then we create a Account class and inherit AbstractBaseUser and create fields in Account class like first_name, last_name, username, email, phone and add some required fields like date_joined, last_logging, is_admin, is_staff, is_active, is_superuser

After creating Account class now we set logging field, currently by default logging field is username, but in our application we want user can logging by using email not username so now we replace username to email USERNAME_FIELD = ‘email’ , REQUIRED_FIELD = [‘username’, ‘email’] and some permission to admin

Next step we create Account manager that manage users account so we create a MyAccountManager() class and inherit BaseUserManager and create a method for users called create_user() and create users.

Once we create class create_user now we create class for superuser create_superuser in MyAccountManager for manage users account

Next, we use the makemigration command to establish a Django database and for utilise models in our database to use migrate command.

once the database has been created, create a superuser and log in to our database.

Use the createsuperuser command to create superuser. then we enter details

of superuser and we can login using email

Source code: Github

Top comments (0)