Henu
개발냥발
Henu
전체 방문자
오늘
어제
  • 분류 전체보기 (411)
    • DevOps (52)
      • Kubernetes (19)
      • Docker (14)
      • AWS (3)
      • Nginx (4)
      • Linux (4)
      • ArgoCD (1)
      • CN (2)
      • NATS (0)
      • Git (5)
    • Back-End (30)
      • Django (18)
      • Spring (5)
      • JPA (1)
      • MSA (5)
    • CS (87)
      • SystemSoftware (20)
      • OS (25)
      • Computer Architecture (16)
      • Network (23)
      • Database (2)
    • Lang (21)
      • Java (9)
      • Python (4)
      • C# (8)
    • Life (12)
    • 블록체인 (2)
    • Algorithm (204)
      • BOJ (160)
      • 프로그래머스 (19)
      • LeetCode (4)
      • SWEA (1)
      • 알고리즘 문제 해결 전략 (8)
      • DS, algorithms (7)
      • Checkio (5)
    • IT (2)

블로그 메뉴

  • GitHub
  • 글쓰기
  • 관리자

공지사항

  • Free!

인기 글

태그

  • BFS
  • Network
  • 다이나믹 프로그래밍
  • DFS
  • docker
  • django
  • 백트래킹
  • boj
  • 프로그래머스
  • Kubernetes

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
Henu

개발냥발

[Django] 회원정보 모델 설계 UserModel design #1
Back-End/Django

[Django] 회원정보 모델 설계 UserModel design #1

2021. 5. 17. 16:29

Django UserModel Design #1

1. 회원정보 모델 생성 - User 모델

회원정보 모델을 사용자 임의로 구성하고 정의하기 위해서 AbstractBaseUser 클래스를 상속받아 User모델을 새롭게 구성했다

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
from django.db import models
from django.contrib.auth.models import AbstractBaseUser
 
class User(AbstractBaseUser):
    
    password = models.CharField(max_length=128)
    username = models.CharField(unique=True, max_length=150)
    is_superuser = models.IntegerField()
    last_name = models.CharField(max_length=128)
    phone = models.CharField(max_length=30)
    email = models.CharField(max_length=256)
    date_of_birth = models.DateTimeField()
    date_joined = models.DateTimeField()
    last_login = models.DateTimeField(blank=True, null=True)
    is_staff = models.IntegerField(blank=True, null=True)
    is_active = models.IntegerField(blank=True, null=True)
    first_name = models.CharField(max_length=30, blank=True, null=True)
    
    objects = UserManager()
    
    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['last_name', 'phone', 'email', 'date_of_birth']
    
    def has_perm(self, perm, obj=None):
        return True
    
    def has_module(self, app_label):
        return True
    
    class Meta:
        db_table = 'auth_user'
 
Colored by Color Scripter
cs

 

- 회원정보 필드 구성<+6 ~ +17> : 기본 auth_user모델에서 새롭게 추가한 phone, date_of_birth를 모델 필드로 추가했다

- User 클래스 객체 생성<+19> : User클래스에 대한 객체 생성 및 사용시 UserManager클래스를 사용한다. (UserManager 클래스는 아래에서 설명한다.)

- USERNAME_FIELD<+21> : 사용자 ID로 사용할 필드를 지정한다.

- REQUIRED_FIELDS<+22> : 필수 입력 필드를 지정한다.

- has_perm(), has_module_perms() <+24 ~ +28> : 관리자 페이지 등과 같은 Django에서 제공하는 패키지의 회원정보 모델을 사용하여 접근 가능 여부에 대한 값을 반환하는 메소드. 둘 다 True를 반환해야 관리자 계정을 생성하고 관리자 페이지를 사용할 수 있다.

- DB테이블 지정<+30 ~ +31> : 회원정보 테이블을 auth_user로 지정한다.


2. 회원정보 모델 객체 생성 - UserManager 클래스

User 모델에 대한 인스턴스를 생성하고 관리하기 위한 클래스(UserManager) 도 재구성을 해야한다.

BaseUserManager 클래스로부터 상속받아서 클래스를 구성했다

사용자 생성을 위한 create_user() 메소드와 관리자 생성을 위한 create_superuser() 메소드도 오버라이딩했다

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.utils import timezone
 
class UserManager(BaseUserManager):
    # Method Overriding
    def create_user(self, username, password, last_name, email, phone, date_of_birth):
        user = self.model(
            username = username,
            last_name = last_name,
            email = self.normalize_email(email),
            phone = phone,
            date_of_birth = date_of_birth,
            date_joined = timezone.now(),
            is_superuser = 0,
            is_staff = 0,
            is_active = 1,
        )
        user.set_password(password)
        user.save(using=self._db)
        
        return user
    
    # Method Overriding
    def create_superuser(self, username, last_name, email, phone, date_of_birth, password):
        user = self.create_user(
            username = username,
            password = password,
            last_name = last_name,
            email = email,
            phone = phone,
            date_of_birth = date_of_birth,
        )
        user.is_superuser = 1
        user.is_staff = 1
        user.save(using=self._db)
        return user
    
Colored by Color Scripter
cs

 

- create_user()<+7 ~ +22> : 사용자 생성 시 회원정보를 파라미터로 받아오고, 기본 auth_user 테이블에는 없는 필드명인 phone, date_of_birth도 모델 필드로 설정하였다

- set_password()<+19> : Django의 비밀번호 생성 메소드를 사용했다.

- save()<+20> : User 모델에서 지정한 테이블인 auth_user에 데이터를 저장한다

- create_superuser()<+25 ~ +37> : create_user()를 실행하여 user정보를 DB에 저장한 후 is_superuser, is_staff 필드의 값을 1로 변경하고 다시 저장함으로써 superuser를 구분한다


3. 회원정보 모델 재구성을 위한 환경 설정

settings.py 에 아래 코드를 추가해야한다.

추가하지 않는다면 User모델을 사용자 모델로 인식하지 못하는 오류가 발생한다.

AUTH_USER_MODEL = '앱이름.user'

 

'Back-End > Django' 카테고리의 다른 글

[Django] ORM 쿼리 최적화 (select_related, annotate, aggregates)  (0) 2021.10.11
[Security] XSS(Cross Site Scripting) 취약점 Django  (0) 2021.09.02
[Django] Google 소셜 로그인 (OAuth2.0)  (13) 2021.09.02
[Django project #2] conda + Django + mysql 개발 환경 구축하기 (2) for Mac  (2) 2021.04.28
[Django project #1] conda + Django + mysql 개발 환경 구축하기 (1) for Mac  (2) 2021.04.26
    'Back-End/Django' 카테고리의 다른 글
    • [Security] XSS(Cross Site Scripting) 취약점 Django
    • [Django] Google 소셜 로그인 (OAuth2.0)
    • [Django project #2] conda + Django + mysql 개발 환경 구축하기 (2) for Mac
    • [Django project #1] conda + Django + mysql 개발 환경 구축하기 (1) for Mac

    티스토리툴바