Create Custom User Model in Django.

Create Custom User Model in Django.

Implement a custom user model in Django using the AbstractBaseUser class

from django.contrib.auth.models import AbstractBaseUser
from django.db import models


class CustomUser(AbstractBaseUser):
email = models.EmailField(unique=True)
username = first_name = last_name = None

USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []

def __str__(self):
return self.email

This custom user model defines an email as the unique identifier for a user and requires the first name and last name as additional fields.

You can then specify your custom user model in the AUTH_USER_MODEL setting in your Django settings file:

AUTH_USER_MODEL = 'your_app_name.CustomUser'

It’s recommended to create a separate app for your custom user model and place the above code in the models.py file of that app.

 


Previous Post Next Post

Contact Form