[Answered ]-How to add an extra field in auth user model in django admin?

1👍

from datetime import datetime
from django.contrib.auth.base_user import BaseUserManager
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import AbstractUser
import uuid
from django.db import models


class CustomUserManager(BaseUserManager):
    """
    Custom user model manager where email is the unique identifiers
    for authentication instead of usernames.
    """
    def create_user(self, email, password, **extra_fields):
        """
        Create and save a User with the given email and password.
        """
        if not email:
            raise ValueError(_('The Email must be set'))
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save()
        return user

    def create_superuser(self, email, password, **extra_fields):
        """
        Create and save a SuperUser with the given email and password.
        """
        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)


class User(models.Model, AbstractUser):
    """Custom user model"""
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, 
         editable=False)
    username = models.UUIDField(default=uuid.uuid4, editable=False)
    email = models.EmailField(_('email address'), unique=True, 
            help_text='User personal unique email')
    date_of_birth = models.DateField(blank=True, null=True)
    last_pass_change = models.DateTimeField(default=datetime.now)
    forgot_password = models.BooleanField(default=False)
    user_ip = models.CharField(default='', max_length=128)
    """You can other fields based on your requirements."""

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    objects = CustomUserManager()

    def __str__(self):
        return self.email

Then add AUTH_USER_MODEL = 'your_app_name.User' in your Django project settings.py file.So from now you will get proper flexibility of User model.So you have to run 2 commands-

python manage.py makemigrations
python manage.py migrate

So from now, you can check from Django admin page or browse the database. I hope this solution might help you.

Leave a comment