본문 바로가기
K-unirank

[Django/K-unirank] User 모델에 필드를 추가하는 깔@롱 쌈@뽕한 법 (feat. 추가한 필드를 admin 페이지에서 확인하는 법)

by 항붕쿤 2024. 4. 11.

리눅스 기준으로 가상환경 폴더 -> lib -> python3.x -> site-packages -> django -> contrib -> auth 폴더로 이동해준 다음 auth폴더에 있는 models.py를 연다. (윈도우도 비슷한 경로로 models.py 파일을 찾아주면 된다.)

그럼 아래 코드가 있을건데

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)


class User(AbstractUser):
    """
    Users within the Django authentication system are represented by this
    model.

    Username and password are required. Other fields are optional.
    """
    class Meta(AbstractUser.Meta):
        swappable = 'AUTH_USER_MODEL'

요 AbstractUser 클래스에 내가 추가하고 싶은 필드를 추가해주면 된다.
추가는 뭐.. 모델에 필드 추가할 때 처럼 추가해주면된다.

왜 User모델이 아니라 AbstractUser 클래스에 추가하냐면
차피 User모델은 AbstractUser 클래스를 상속하기 때문에 AbstractUser 클래스에 값이 추가되면 자동적으로 User에도 값이 추가되기 때문이다.

수정이 끝난 후에는 python manage.py makemigrations랑 python manage.py migrate 명령어를 꼭 실행하자

명령어를 실행한 후 추가한 필드들을 어드민 페이지에서도 보고 수정할 수 있게 하려면 같은 폴더의 admin.py 파일을 수정해야 한다.
admin.py 파일을 열고 좀 훑어보면 아래 코드가 있을건데

@admin.register(User)
class UserAdmin(admin.ModelAdmin):
    add_form_template = 'admin/auth/user/add_form.html'
    change_user_password_template = None
    fieldsets = (
        (None, {'fields': ('username', 'password')}),
        (_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}),
        (_('Permissions'), {
            'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions'),
        }),
        (_('Important dates'), {'fields': ('last_login', 'date_joined')}),
    )

요 fieldsets 튜플에 내가 추가한 필드의 변수명을 넣어주면 된다.

@admin.register(User)
class UserAdmin(admin.ModelAdmin):
    add_form_template = 'admin/auth/user/add_form.html'
    change_user_password_template = None
    fieldsets = (
        (None, {'fields': ('username', 'password')}),
        (_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}),
        (_('Permissions'), {
            'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions'),
        }),
        (_('Important dates'), {'fields': ('last_login', 'date_joined')}),
        (_('University'), {'fields': ('is_university_certificated', 'university')})
    )

(대충 요런 느낌으로)