본문 바로가기
내일배움캠프/Django

DRF - 2

by useSword 2024. 5. 2.

[회원가입]

1. settings.py

AUTH_USER_MODEL = 'accounts.Accounts'
AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]






2. models.py

from django.contrib.auth.models import AbstractUser
from django.db import models


class Accounts(AbstractUser):
    email = models.EmailField(
        default='', max_length=100, null=False, blank=False, unique=True)
    nickname = models.CharField(
        default='', max_length=100, null=False, blank=False, unique=True)
    name = models.CharField(default='', max_length=100,
                            null=False, blank=False)
    birth_date = models.DateField()
    gender = models.CharField(max_length=1, choices=(
        ('M', 'Male'), ('F', 'Female')), blank=True)
    features = models.TextField(blank=True)




3. accounts/serializers.py

from rest_framework import serializers
from django.contrib.auth.hashers import make_password
from .models import Accounts


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = Accounts
        fields = ['username', 'email', 'name', 'nickname',
                  'birth_date', 'gender', 'features', 'password']
        extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):
        user = Accounts.objects.create(
            username=validated_data['username'],
            email=validated_data['email'],
            name=validated_data['name'],
            nickname=validated_data['nickname'],
            birth_date=validated_data.get('birth_date'),
            gender=validated_data.get('gender', ''),
            features=validated_data.get('features', ''),
            password=make_password(validated_data['password'])
        )
        user.save()
        return user




4. urls.py

 

from django.urls import path
from . import views

app_name = "accounts"
urlpatterns = [
    path('signup/', views.accounts_signup, name='signup'),
]



5. views.py

User = get_user_model()


@api_view(["GET"])
def accounts_signup(self, email, nickname, name, password=None):
    if not email:
        raise ValueError('must have user email')
    if not nickname:
        raise ValueError('must have user nickname')
    if not name:
        raise ValueError('must have user name')
    user = self.model(
        email=self.normalize_email(email),
        nickname=nickname,
        name=name
    )
    user.set_password(password)
    user.save(using=self._db)
    return user


post를 값을 아래와 같이 넣으면 됨.

{
    "email": 
        "1489ehdghks@gmail.com"
    ,
    "username": 
        "usesword"
    ,
    "name": 
        "김동환"
    ,
    "nickname": 
        "usesword"
    ,
    "birth_date": 
        "1996-05-27"
    ,
    "password": 
        "14538259"
    
}




[리프레쉬 토큰]

1. urls.py에 코드 추가

from rest_framework_simplejwt.views import (
    TokenObtainPairView,
    TokenRefreshView,
)

    path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),


{
  "username": "admin",
  "password" : "admin1234"
}




[LOGIN (JWT TOKEN)]


INSTALLED_APPS에 추가
    'rest_framework',
    'rest_framework.authtoken',

마이그레이션 진행
python manage.py migrate


왜 python manage.py makemigrations은 안함?
>>>rest_framework.authtoken과 같이 사전에 제공된 Django 애플리케이션이나 타사 애플리케이션의 경우, 필요한 마이그레이션 파일들이 이미 애플리케이션과 함께 제공


언제 makemigrations를 실행해야 하나요?
새로운 모델을 추가했을 때: 자신의 프로젝트에 새로운 Django 모델을 추가하거나 기존 모델을 수정했을 경우, 이 변경 사항을 데이터베이스 스키마에 반영하기 위해 makemigrations를 실행해야 합니다.
모델의 변경 사항이 있을 때: 모델의 필드를 추가, 삭제 또는 변경하는 등 모델 구조에 변화가 있을 경우에도 실행합니다.
관계형 필드의 변경이 있을 때: ForeignKey, ManyToManyField 등의 관계형 필드에 변경이 있는 경우에도 마이그레이션 파일을 생성해야 합니다.



[블랙 리스트]

 

1. INSTALLED_APPS에 추가
'rest_framework_simplejwt.token_blacklist',

 

 

2. 마이그레이션

python manage.py migrate

 

3. DB 확인하면 아래가 2개가 나타남.

rest_framework_simplejwt.token_blacklist

token_blacklist_outstandingtoken

'내일배움캠프 > Django' 카테고리의 다른 글

DRF - 3  (0) 2024.05.02
DRF  (0) 2024.05.01
Django 8일차  (1) 2024.04.19
Django 7일차  (1) 2024.04.19
Django 5일차  (0) 2024.04.17