본문 바로가기

Web/Django

[Django, React] 로그인, 회원가입 연동 (1)

simplejwt를 사용했는데 어떻게 인증되는 건지 궁금함

 

내 프로젝트의 views.py

from django.contrib.auth import get_user_model
from django.shortcuts import render
from rest_framework.permissions import AllowAny
from rest_framework.generics import CreateAPIView
from .serializers import SignupSerializer

class SignupView(CreateAPIView):
    model = get_user_model()
    serializer_class = SignupSerializer
    permission_classes = [AllowAny]
  • CreateAPIView는 모델 생성을 위한 view고, 아래 코드에서 나오듯 post를 제공하며 create함수를 호출함
  • get_user_model()은 settings의 AUTH_USER_MODEL 을 불러옴 

라이브러리의 generics.py 

class CreateAPIView(mixins.CreateModelMixin,
                    GenericAPIView):
    """
    Concrete view for creating a model instance.
    """
    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)

 

.../django/contrib/auth/__init__.py

def get_user_model():
    """
    Return the User model that is active in this project.
    """
    try:
        return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False)
    except ValueError:
        raise ImproperlyConfigured(
            "AUTH_USER_MODEL must be of the form 'app_label.model_name'"
        )
    except LookupError:
        raise ImproperlyConfigured(
            "AUTH_USER_MODEL refers to model '%s' that has not been installed"
            % settings.AUTH_USER_MODEL
        )

 

urls.py

from django.urls import path
from rest_framework_simplejwt.views import (TokenObtainPairView, TokenRefreshView, )
from . import views

urlpatterns = [
    path('signup/', views.SignupView.as_view(), name='login'),
    path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
]

 

serializers.py

from rest_framework import serializers
from django.contrib.auth import get_user_model

User = get_user_model()

class SignupSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True)

    def create(self, validated_data):
        user = User.objects.create(username=validated_data["username"])
        user.set_password(validated_data["password"])
        user.save()
        return user
    
    class Meta:
        model = User
        fields = ['pk', 'username', 'password']
  • Model Meta Option에 대해서
    • (내 프로젝트의 경우) db 테이블 이름을 override하려면, class Meta 내에 <db_table_name> 파라미터 사용
    • 이 외에 app_label을 붙인다든가 db_table_comment를 이용해 주석을 달아주는 등 다양한 옵션이 있음
    • https://docs.djangoproject.com/en/5.0/ref/models/options/  참고
 

Django

The web framework for perfectionists with deadlines.

docs.djangoproject.com

 


리액트와 연동 과정은 2편으로