Skip to content

Instantly share code, notes, and snippets.

@yashpatel-py
Last active September 3, 2022 13:57
Show Gist options
  • Save yashpatel-py/4d700d4501fab10fd44aa7b617bb7fde to your computer and use it in GitHub Desktop.
Save yashpatel-py/4d700d4501fab10fd44aa7b617bb7fde to your computer and use it in GitHub Desktop.
In this Gist I have given code for creating custom user model for django.

Django Custom user model

  1. Create virtual environment using python -m venv env

  2. Activate virtual environment using command(for linux users) source .\env\bin\activate

  3. Activate virtual environment using command(for windows users) .\env\Script\activate

  4. Install django pip install django

  5. Create project django-admin startproject <yourproject>

  6. Go to project directory and create app python manage.py startapp account

  7. In account folder go to models.py and write below code.

account/models.py

from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.db import models
from django.utils.translation import gettext_lazy as _
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager

class CustomAccountManager(BaseUserManager):
    '''
        to create ADMIN USER
    '''
    def create_superuser(self, email, username, first_name, last_name, password, **other_fields):
        other_fields.setdefault('is_staff', True)
        other_fields.setdefault('is_admin', True)
        other_fields.setdefault('is_superuser', True)
        other_fields.setdefault('is_active', True)

        if other_fields.get('is_staff') is not True:
            raise ValueError(_('Superuser must be assigned to is_staff=True.'))

        if other_fields.get('is_admin') is not True:
            raise ValueError(_('Superuser must be assigned to is_admin=True.'))

        if other_fields.get('is_superuser') is not True:
            raise ValueError(_('Superuser must be assigned to is_superuser=True.'))

        return self.create_user(email, username, first_name, last_name, password, **other_fields)

    '''
        TO CREATE Normal User
    '''
    def create_user(self, email, username, first_name, last_name, password, **other_fields):
        other_fields.setdefault('is_active', True)

        if not email:
            raise ValueError(_('You must provide an email address'))

        email = self.normalize_email(email)

        user = self.model(email=email, username=username, first_name=first_name, last_name=last_name, **other_fields)
        user.set_password(password)
        user.save()
        return user

class Account(AbstractBaseUser, PermissionsMixin):
    first_name = models.CharField(max_length=150)
    last_name = models.CharField(max_length=150)
    username = models.CharField(max_length=150, unique=True)
    email = models.EmailField(_('email address'), unique=True)
    profile_image = models.ImageField(upload_to="profile_image/", blank=True)
    date_joined = models.DateTimeField(verbose_name="date joined", auto_now_add=True)
    last_login = models.DateTimeField(verbose_name="last login", auto_now=True)

    is_staff = models.BooleanField(default=False)
    is_admin = models.BooleanField(default=False)
    is_active = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)

    objects = CustomAccountManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username', 'first_name', 'last_name']

    def __str__(self):
        return self.username

    def full_name(self):
        return f"{self.first_name} {self.last_name}"

    def has_perm(self, perm, obj=None):
        return self.is_admin
    
    def has_module_perms(self, app_label):
        return True

account/admin.py

from django.contrib import admin
from .models import Account

admin.site.register(Account)

<project_name_folder>/settings.py

INSTALLED_APPS = [
    'account',
]

# your app_name.your_user_model_name ---> EG: class Account
AUTH_USER_MODEL = "account.Account"
  1. Now open terminal and run command python manage.py makemigrations

  2. After above command and run python manage.py migrate

  3. In order to login in admin panel you need to create superuser and to create superuser run this command python manage.py createsuperuser and give your email and other information.

  4. Now run the server by using python manage.py runserver

  5. Now navigate to http://localhost:8000/admin/ and provide email and password

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment