코딩 개발일지

장고(Django) AbstractBaseUser의 models.py / admin.py 본문

AI 본 교육/AI 7주차

장고(Django) AbstractBaseUser의 models.py / admin.py

호기호 2023. 9. 27. 02:17

장고가 기본 제공하는 user model을 쓰려면 AbstractUser 을 쓰면 된다. 간단한 프로젝트에서만 쓸듯?!

기본제공하는거 말고, custom을 해주고싶다면, AbstractBaseUser 를 써야한다.

그래서 보통은 AbstractBaseUser 를 쓰는게 좋다.

 

공식문서에서 AbstractBaseUser 를 admin.py와 models.py에 복사해서 넣어주고 custom 해주면 된다.

https://docs.djangoproject.com/en/4.2/topics/auth/customizing/

 

Django

The web framework for perfectionists with deadlines.

docs.djangoproject.com


models.py

그대로 복사해서 쓰면,

class MyUserManager(BaseUserManager):
    def create_user(self, email, date_of_birth, password=None):
        """
        Creates and saves a User with the given email, date of
        birth and password.
        """
        if not email:
            raise ValueError("Users must have an email address")

        user = self.model(
            email=self.normalize_email(email),
            date_of_birth=date_of_birth,
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, date_of_birth, password=None):
        """
        Creates and saves a superuser with the given email, date of
        birth and password.
        """
        user = self.create_user(
            email,
            password=password,
            date_of_birth=date_of_birth,
        )
        user.is_admin = True
        user.save(using=self._db)
        return user

create_user 는 user를 생성할 때, 필요한 정보를 넣는 곳이다.

class MyUserManager(BaseUserManager):
    def create_user(self, email, date_of_birth, fullname, nickname, password=None):
        """
        Creates and saves a User with the given email, date of
        birth and password.
        """
        if not email:
            raise ValueError("Users must have an email address")
        if not fullname:
            raise ValueError('must have user fullname')
        if not nickname:
            raise ValueError('must have user nickname')

        user = self.model(
            email=self.normalize_email(email),
            date_of_birth=date_of_birth,
            fullname=fullname,
            nickname=nickname,
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

이런식으로 fullname, nickname 등을 추가할 수 있다.

create_superuser 도 마찬가지!!

다음!!!!!!!!

class MyUser(AbstractBaseUser):
    email = models.EmailField(
        verbose_name="email address",
        max_length=255,
        unique=True,
    )
    date_of_birth = models.DateField()
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)

    objects = MyUserManager()

    USERNAME_FIELD = "email"
    REQUIRED_FIELDS = ["date_of_birth"]

    def __str__(self):
        return self.email

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

    @property
    def is_staff(self):
        "Is the user a member of staff?"
        # Simplest possible answer: All admins are staff
        return self.is_admin

class MyUser는 database에 저장되는 columm을 생성해준다.

class User(AbstractBaseUser):
    email = models.EmailField(
        verbose_name="email address",
        max_length=255,
        unique=True,
    )
    date_of_birth = models.DateField()
    followings = models.ManyToManyField(
        'self', symmetrical=False, related_name="followers", blank=True)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)
    fullname = models.CharField(max_length=100)
    nickname = models.CharField(max_length=100)

    objects = MyUserManager()

    USERNAME_FIELD = "email"
    REQUIRED_FIELDS = ["date_of_birth", "nickname", "fullname"]

마찬가지로 fullname, nickname, followings 같은것들 추가해줄 수 있다.


admin.py

마찬가지로 공식문서에서 일부만 가져와보자.

class UserAdmin(BaseUserAdmin):
    # The forms to add and change user instances
    form = UserChangeForm
    add_form = UserCreationForm

    # The fields to be used in displaying the User model.
    # These override the definitions on the base UserAdmin
    # that reference specific fields on auth.User.
    list_display = ["email", "date_of_birth", "is_admin"]
    list_filter = ["is_admin"]
    fieldsets = [
        (None, {"fields": ["email", "password"]}),
        ("Personal info", {"fields": ["date_of_birth"]}),
        ("Permissions", {"fields": ["is_admin"]}),
    ]
    # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
    # overrides get_fieldsets to use this attribute when creating a user.
    add_fieldsets = [
        (
            None,
            {
                "classes": ["wide"],
                "fields": ["email", "date_of_birth", "password1", "password2"],
            },
        ),
    ]
    search_fields = ["email"]
    ordering = ["email"]
    filter_horizontal = []
    list_display = ["id", "email", "is_admin",
                    "date_of_birth", "fullname", "nickname"]

list_display 를 고쳐주면, user정보의 썸네일(?ㅋㅋ)을 바꿔줄 수 있다.

 

    fieldsets = [
        ("유저정보", {"fields": ["email", "password",
         "date_of_birth", "fullname", "nickname"]}),
        ("Permissions", {"fields": ["is_admin"]}),
    ]

fieldsets 을 고쳐주면, user정보에 들어갔을 때의 화면에 추가된다.