서버(Server)/장고 (Django)

Django AbstractUser 불필요한 필드 지우는 방법

Wibaek 2023. 1. 4. 20:57
728x90

Django의 유저 모델들

Django에서는 기본적으로 유저 모델 django.contrib.auth.models의 User를 제공하고, 이를 통해 간편하게 인증 등을 처리할 수 있다. 또한 기본제공되는 유저모델을 확장할 수 있게 다음과 같은 다양한 방법이 있다.

  • User에 기반한 Proxy Model 생성하기
  • 1:1 로 User에 연결된 모델 만들기
  • AbstractUser 상속받아 커스텀 유저 모델 만들기
  • AbstractBaseUser 상속받아 커스텀 유저 모델 만들기

AbstractUser 모델

기본적으로 제공하는 django.contrib.auth.models의 User을 사용하더라도, 이후에 유저 모델을 수정할 일이 생길수있다. 그런데 이후에 이를 수정한다면 그 과정이 매우 힘들기에, 기본적으로 AbstractUser를 상속한 유저를 다음과 같이 새로 만들어 사용하는것을 추천한다. (기본제공하는 User도 그냥 AbstractUser를 상속받기만 한 형태이다.)

# models.py
from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    pass

다음과 같이 선언만 해두더라도, 이후에 수정하기 용이하기에 프로젝트 시작 시 유용하다.

AbstractUser는 다음과 같이 정의되어 있다.

# django.contrib.auth.models
class AbstractUser(AbstractBaseUser, PermissionsMixin):
    """
    An abstract base class implementing a fully featured User model with
    admin-compliant permissions.

    Username and password are required. Other fields are optional.
    """

    username_validator = UnicodeUsernameValidator()

    username = models.CharField(
        _("username"),
        max_length=150,
        unique=True,
        help_text=_(
            "Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only."
        ),
        validators=[username_validator],
        error_messages={
            "unique": _("A user with that username already exists."),
        },
    )
    first_name = models.CharField(_("first name"), max_length=150, blank=True)
    last_name = models.CharField(_("last name"), max_length=150, blank=True)
    email = models.EmailField(_("email address"), blank=True)
    is_staff = models.BooleanField(
        _("staff status"),
        default=False,
        help_text=_("Designates whether the user can log into this admin site."),
    )
    is_active = models.BooleanField(
        _("active"),
        default=True,
        help_text=_(
            "Designates whether this user should be treated as active. "
            "Unselect this instead of deleting accounts."
        ),
    )
    date_joined = models.DateTimeField(_("date joined"), default=timezone.now)

    objects = UserManager()

    EMAIL_FIELD = "email"
    USERNAME_FIELD = "username"
    REQUIRED_FIELDS = ["email"]

    class Meta:
        verbose_name = _("user")
        verbose_name_plural = _("users")
        abstract = True

    def clean(self):
        super().clean()
        self.email = self.__class__.objects.normalize_email(self.email)

    def get_full_name(self):
        """
        Return the first_name plus the last_name, with a space in between.
        """
        full_name = "%s %s" % (self.first_name, self.last_name)
        return full_name.strip()

    def get_short_name(self):
        """Return the short name for the user."""
        return self.first_name

    def email_user(self, subject, message, from_email=None, **kwargs):
        """Send an email to this user."""
        send_mail(subject, message, from_email, [self.email], **kwargs)

username, email, first_name, last_name 등 다양한 필드가 기본적으로 정의되어 있는데, 이중에 사용하지 않을 필드도 여럿 있을 것이다. 이때 이런 필드들을 지우기 위해서는 다음과 같이 오버라이딩 해주면 된다.

# models.py
class User(AbstractUser):
    first_name = None
    last_name = None
    
    email = None
    EMAIL_FIELD = None
    REQUIRED_FIELDS = []

# 이메일 필드 삭제시에는 UserManager도 바꿔주어야 한다
# https://docs.djangoproject.com/en/4.1/topics/auth/customizing/#a-full-example

이렇게 대부분의 기능을 사용하지 않는다면 AbstractBaseUser에도 인증기능이 있기에 이를 상속받는 것도 추천한다.

728x90