Custom User Modal Creation in Django

Hi, Welcome back Techy Mind...

In this Discussion, I'm going to chew over on Custom User Modal...

Let's flow as points:

1: We have to import some keys as below.

from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin, User

2: Now we have to create a function by extending the keys with the named Account (as preferred) and add only the required field but i have something to say we will get some fields even though not added in the modal, like password and is_superuser.

   from django_mysql.models import EnumField
class Account(AbstractBaseUser, PermissionsMixin):
    name = models.CharField(max_length=255, null=False, verbose_name="Full Name")
    user_name = models.CharField(max_length=255, null=False, verbose_name="User Name")
    email = models.EmailField(max_length=60, null=True, blank=True, verbose_name="Email")
    token_id = models.TextField(null=True, blank=True)
    mobile_number = models.CharField(max_length=10, null=False,unique=True, verbose_name="Mobile")
    last_login  = models.DateTimeField(auto_now=True)
    EXIST_CHOICES = [
        ('1', '1'),
        ('0', '0')
    ]
    is_blocked = EnumField(choices = EXIST_CHOICES, default='0')
    is_active = EnumField(choices = EXIST_CHOICES, default='1')
    is_exists = EnumField(choices = EXIST_CHOICES, default='1')
    created_datetime = models.DateTimeField(auto_now_add=True)
    updated_datetime = models.DateTimeField(auto_now=True)

    USERNAME_FIELD = 'mobile_number'
    REQUIRED_FIELDS = ['name']

    objects = MyUserManager()
    
    class Meta:
        db_table = 'user'
        unique_together = [ 'mobile_number']
#i made mobile_number as unique 
    def __str__(self):
        return self.name
    def has_perm(self, perm, obj=None):
        return self.is_admin

    def has_module_perms(self, app_label):
        return True

3: After creating Modal we have to create a UserManager class with the name MyUserManager(BaseUserManager)

from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin, User
# Create your models here.
class MyUserManager(BaseUserManager):
    def create_user(self, email, name, mobile_number,username):
        if not name:
            raise ValueError('Name cannot be empty')

        if not mobile_number:
            raise ValueError('Mobile cannot be empty')

        user = self.model(
            email = self.normalize_email(email),
            name = name, 
           user_name= username, 
            mobile_number = mobile_number
        )
        if password:
            user.set_password(password)
        
        user.is_active = 1
        user.is_superuser = 0
        user.save(using=self._db)
        return user


    def create_superuser(self, email='', name='', mobile_number='', password=''):
        # converts email charecters to lower case
        user = self.model(email=self.normalize_email(email), name=name, mobile_number = mobile_number, password=password)
        user.is_admin = 1
        user.is_active = 1
        user.is_staff = 1
        user.is_superuser = 1
        role_id = Role.objects.get(id=1)
        user.role_id = role_id
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_admin(self, email='', name='', mobile='', password=''):
        # converts email charecters to lower case
        user = self.model(email=self.normalize_email(email), name=name, mobile = mobile, password=password)
        user.is_admin = 1
        user.is_active = 1
        user.is_staff = 1
        user.is_superuser = 0
        user_role = UserRole.objects.get(id=1)
        user.user_type = user_role
        user.set_password(password)
        user.save(using=self._db)
        return user

4: Then makemigrations and migrate...

Print("Thank You!")

output:

Thank You!

Sign In or Register to comment.