django custom user model and custom admin

◾️ Substituting a custom User model

◾️ create user app for custom user

django-admin startapp users

◾️ settings.py

 PROJECT_APPS = [“users.apps.UsersConfig”,]

 AUTH_USER_MODEL = “users.User”

DJANGO_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
]

PROJECT_APPS = [
    "users.apps.UsersConfig",
]

INSTALLED_APPS = DJANGO_APPS + PROJECT_APPS


...

AUTH_USER_MODEL = "users.User"

◾️ Custom User Model

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


# Create your models here.
class User(AbstractUser):
    """ Custom User Model """

    GENDER_MALE = "male"
    GENDER_FEMALE = "female"
    GENDER_OTHER = "other"

    GENDER_CHOICES = (
        (GENDER_MALE, "Male"),
        (GENDER_FEMALE, "Female"),
        (GENDER_OTHER, "Other"),
    )

    .....

    avatar = models.ImageField(null=True, blank=True)
    gender = models.CharField(
        choices=GENDER_CHOICES, max_length=10, null=True, blank=True
    )
    bio = models.TextField(default="", blank=True)
    birthday = models.DateField(null=True)
    language = models.CharField(choices=LANG_CHOICES, max_length=2, blank=True)
    currency = models.CharField(choices=CURRENCY_CHOICES, max_length=3, blank=True)
    superhost = models.BooleanField(default=False)

◾️ show custom user model with admin panel

from django.contrib import admin
from . import models


# Register your models here.
# https://docs.djangoproject.com/en/3.2/ref/contrib/admin/
@admin.register(models.User)
class CustomUserAdmin(admin.ModelAdmin):
    """ Custom User Admin """

    list_display = ("username", "email", "gender", "language", "currency", "superhost")
    list_filter = ("language", "currency", "superhost")

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です