장고엔 이미 구현된 로그인 기능이 있다.
유저를 표현하기 위한 주요 attribute들은 다음과 같다.
- username
- password
- first_name
- last_name
docs.djangoproject.com/en/3.1/topics/auth/default/
Using the Django authentication system | Django documentation | Django
Django The web framework for perfectionists with deadlines. Overview Download Documentation News Community Code Issues About ♥ Donate
docs.djangoproject.com
그런데 로그인한 유저의 정보를 표현하기 위한 attribute에 추가 정보를 넣고 싶은 경우가 생기면 어떻게 해야할까?
공식문서에 따르면 AbstractUser 모델을 상속하여 커스텀할 수 있다고 한다.
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class CustomUser(AbstractUser):
term = models.CharField(max_length=25, null=True)
division = models.CharField(max_length=25, null=True)
phone_number = models.CharField(max_length=25, null=True)
간단한 예제 코드이다. AbstractUser 클래스를 상속받아 커스텀 유저 모델을 만들 수 있다. term, division, phone_number를 추가로 저장할 수 있게 되었다.
이제 Form에 적용하는 코드를 살펴보자
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import *
class UserForm(UserCreationForm):
email = forms.EmailField(label="이메일")
division = forms.CharField(max_length=25)
term = forms.CharField(max_length=25)
phone_number = forms.CharField(max_length=25)
class Meta:
model = CustomUser
fields = ("username", "email", "term", "division", "phone_number")
UserCreationForm을 상속받아 UserForm을 만들고 CustomUser 모델로 저장하겠다는 의미이다.
마이그레이션을 적용해보자
python manage.py makemigrations
python manage.py migration
적용하면 DB에 [앱이름]_customuser란 이름의 테이블이 생성된걸 확인할 수 있다.
+추가: 간혹 커스텀 유저모델을 추가하고 마이그레이션 과정에서 오류가 날 때가 있다. 그럴 땐 마이그레이션 파일들을 __init__.py만 제외하고 지운 후에 다시 시도해보자
'Django' 카테고리의 다른 글
Django Inspectdb 기능 (0) | 2020.12.04 |
---|---|
Django Model _set 메서드에 관하여 (0) | 2020.11.17 |