Use Customized User Profile to Replace Django Default User Tables

In Django, the default user profile table is created as auth_user. Alternatively, we can create our own customized UserProfile to replace Django default auth_user table.

Define UserProfile Model

After creating the users app, in the models.py file, define the UserProfile model. I will inherit Django’s AbstractUser

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

GENDER_CHOICES = (
    ("M", "Male"),
    ("F", "Female")
)


# Create your models here.
class UserProfile(AbstractUser):
    nick_name = models.CharField(max_length=50, null=True, blank=True)
    birthday = models.DateField(null=True, blank=True)
    gender = models.CharField(choices=GENDER_CHOICES, max_length=6)
    address = models.CharField(max_length=100, default="")
    mobile = models.CharField(max_length=11, unique=True)
    image = models.ImageField(upload_to="head_image/%Y/%m", default="head_image/default.jpg")

    class Meta:
        verbose_name = "User Profile"

    def __str__(self):
        if self.nick_name:
            return self.nick_name
        return self.username

Configure Settings

In the project settings.py file, add the following

AUTH_USER_MODEL = "users.UserProfile"

Make migrations and migrate

In the shell, make migrations and migrate

python manage.py makemigrations
python manage.py migrate

Now, users_userprofile table will replace Django’s default auth_user table as the user management table.


   Reprint policy


《Use Customized User Profile to Replace Django Default User Tables》 by Isaac Zhou is licensed under a Creative Commons Attribution 4.0 International License
  TOC