Ad Code

Ticker

6/recent/ticker-posts

How to create custom user model in django python

In the python Django framework, some time developer wants to add extra information in the user model, then the method available is to create an associated model to reference from the available user model or you can add and manage using your own model write and use as user model for every type of users logins.

How to create custom user model in django python

Setup python environment

  1. create root directory of the project in you local system and run the following command in cmd of the root directory of the project which directory to make to project.

    python -m venv [path of the project directory or name of the environment]
  2. For example, I want to create venv name environment directory then run the following code in the root directory.
    python -m venv venv
  3. After setup environment, you can activate your environment in the cmd
    .\venv\Scripts\activate [for windows users only in the project root directory]
    for another os user can follow the below commands:-
    For Linux os:- source ./venv/bin/activate
  4. After activating the environment install the Django package using the pip command
    pip install Django
  5. After installing this command you make a project using the Django command and create an app also
    django-admin startproject mysite
    the following command is to create a project named is mysite
  6. After creating the project you also create an app using the command of Django
  7. Before creating a project app go to the mysite directory (in my case project name is mysite)
  8. Run and create an app inside the project directory
    python manage.py startapp users
    in this command, the user is the app name in the project directory.
  9. after running this inside your project directory is will create users directory with predefined structure files in the users directory.
  10. After completing these points you may go to create and define the custom model for the user and manager for the custom model user.

Make custom models using custom user model managers

Creating the managers.py in the users app

managers.py
from django.contrib.auth.base_user import BaseUserManager
from django.utils.translation import gettext_lazy as _
from validate_email import validate_email

class UserManager(BaseUserManager):
    def create_user(self, email, password, **extra_fields):
        if not email:
            raise ValueError(_('The Email must be set'))
        email = self.normalize_email(email)
        if not validate_email(email):
            raise ValueError(_('Invalid email set'))
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save()
        return user

    def create_superuser(self, email, password, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        extra_fields.setdefault('is_active', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError(_('Superuser must have is_staff=True.'))
        if extra_fields.get('is_superuser') is not True:
            raise ValueError(_('Superuser must have is_superuser=True.'))
        return self.create_user(email, password, **extra_fields)

In this file, you can see the two functions one is create_user and another is create_superuser.
The first one is the normal user creating process in the project to define as you wone code.
Another won is to define to register the superuser only.
In the above function, you can decide your own logic as you want to decide for users and users model fields.

Creating the models.py in the users app

models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.translation import gettext_lazy as _
from . import managers


class User(AbstractUser):
    username = None
    email = models.EmailField(_('email address'), unique=True)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    objects = managers.UserManager()

    gender = models.CharField(
        max_length=140,
        null=True,
        choices=(
            ('Male', 'Male'),
            ('Female', 'Female'),
            ('Other', 'Other')
        )
    )
    dob = models.DateField(blank=True, null=True)
    
    class Meta:
        verbose_name_plural = 'Users'
        ordering = ("email",)
    
    def __str__(self):
        return self.email
This file code has the users model define the field with extra data according to project requirements.
In this project calling manager file to assign model manager for the users using the following code:-
from . import managers
.....
objects = managers.UserManager()

In this model structure, you can also define which field works as a username field.
The following code is to decide the custom user model in the Django project.

Assign custom model as the user model

The above code is to defines the model class, manager, and database structure of the user.
But this code is not defined as a Django user model because this is not connected to the project setting and does not define which model is used for the custom model.

This model is defined in the setting.py in the project directory to set as a user model.
settings.py
AUTH_USER_MODEL = 'users.User' #here is the users app to define the user model
After this, you can make migrations and migrate the code and database file to create tables.

In the above explanation, I would define the Django project custom model, custom filed assigned in the user table, and custom user manager for every type of user. Also, you can extend the user table field in the model user class which is created for a custom model.

Post a Comment

0 Comments

Ad Code