Django User Models

Default user model

1) Django has a default usermodel automatically created.

2) This can be viewed through the admin interface under the table name User

3) Within the code, this model object can be accessed as

from django.contrib.auth import get_user_model
user = get_user_model()

4) To create a new user, (default usermodel requires mandatory username)

user = get_user_model().objects.create_user(
            username=username,
            password=password
        )

Custom user model

Most of the time, we may want to differ from the default user model. For eg, we may want to add extra fields, or make email mandatory instead of username

1) For this, we create a new model class extending django.contrib.auth.models.AbstractBaseUser and django.contrib.auth.models.PermissionMixin

2) In this class, we have to set the attribute object to a UserManager class which defines a model with mandatory fields. We should then add method create_user to this class and we should be able to create new user as

User.object.create_user('xyz@am.com','1234')

from django.db import models
    from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, \
                                                PermissionsMixin


    # Creating CUSTOM USER MODEL
    class UserManager(BaseUserManager):
        """Default User model requires mandatory username field
        But we dont want it that way. So we create custom User model"""

        def create_user(self, email, password=None, **kwargs):
            """Creates and saves a new user and returns the user model"""

            user = self.model(email=email, **kwargs)
            user.set_password(password)
            user.save(using=self._db)

            return user


    class User(AbstractBaseUser, PermissionsMixin):
        """Custom user model that supports using email instead of password"""

        ##all the fields we ll need
        email = models.EmailField(max_length=255, unique=True)
        name = models.CharField(max_length=255)
        is_active = models.BooleanField(default=True)
        is_staff = models.BooleanField(default=False)

        objects = UserManager()

        USERNAME_FIELD = 'email'

3) In settings.py, set

AUTH_USER_MODEL = 'APP_NAME.User'

NOTE: Email field is still not mandatory. We ll add this functionality in next section while explaining Test driven development