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/ 참고
리액트와 연동 과정은 2편으로
'Web > Django' 카테고리의 다른 글
[Django] Django, PostgreSQL 연동하기 (0) | 2024.05.24 |
---|---|
[Django, React] 로그인, 회원가입 연동 (2) (0) | 2024.03.07 |
[Django] JWT 인증 (2) | 2024.03.04 |
[Django] Rest Framework란, serializer, view 등 (0) | 2024.03.04 |
[Django] 앱 생성, 동작 flow (0) | 2024.03.03 |