drf ๋ฐฑ์๋๊ฐ๋ฐ + ํ๋ก ํธ๊ฐ๋ฐ
: ์ด๋ฒ ํ๋ก์ ํธ๋ ํํ๋ก์ ํธ๋ก ์์ํฉ๋๋ค.
serializers.py
from rest_framework import serializers
from article.models import (
Article as ArticleModel,
Comment as CommentModel,
CommentLikeBridge,
ArticleVoteBridge,
)
from user.models import User as User
from user.serializers import UserSerializer
class CommentSerializer(serializers.ModelSerializer):
comments_related_article = serializers.SerializerMethodField()
author = serializers.SerializerMethodField()
count = serializers.SerializerMethodField()
nickname = serializers.SerializerMethodField()
def get_comments_related_article(self,obj):
return obj.article.id
def get_author(self,obj):
return obj.comment_author.username
def get_nickname(self,obj):
return obj.comment_author.nickname
def get_count(self,obj):
like_count = CommentLikeBridge.objects.filter(comment_id=obj.id).count()
return like_count
# custum update
def update(self, instance, validated_data):
for key, value in validated_data.items():
if key == "comment_author":
instance.user(value)
continue
setattr(instance, key, value)
instance.save()
return instance
class Meta :
model = CommentModel
fields = ['id', 'article', 'author','nickname', 'comment_created_at', 'comment_contents', 'comments_related_article', 'count']
class ArticleSerializer(serializers.ModelSerializer):
comment_set = CommentSerializer(many=True)
author = serializers.SerializerMethodField()
vote = serializers.SerializerMethodField()
nickname = serializers.SerializerMethodField()
def get_author(self,obj):
return obj.article_author.username
def get_nickname(self,obj):
return obj.article_author.nickname
def get_vote(self,obj):
votes = ArticleVoteBridge.objects.filter(article_id=obj.id)
votes = list(votes.values())
vote_count = dict(fox=0, green=0, miss=0)
for vote in votes:
if vote['category'] == 'ํญ์ค์
๋๋ค':
vote_count['fox'] += 1
elif vote['category'] == '๊ทธ๋ฆฐ๋ผ์ดํธ':
vote_count['green'] += 1
else:
vote_count['miss'] += 1
return vote_count
# custum update
def update(self, instance, validated_data):
for key, value in validated_data.items():
if key == "article_author":
instance.set_author(value)
continue
setattr(instance, key, value)
instance.save()
return instance
class Meta:
model = ArticleModel
fields = ['id','author','nickname','article_title','article_image', 'board', 'vote',
'article_contents','article_post_date',
'article_exposure_date','comment_set',
]
views.py
from rest_framework import permissions, status
from rest_framework.views import APIView
from rest_framework.response import Response
from django.contrib.auth import login, logout, authenticate
from rest_framework_simplejwt.authentication import JWTAuthentication
from user.jwt_claim_serializer import TokenObtainPairSerializer
from rest_framework_simplejwt.views import TokenObtainPairView
from user.models import (
User as UserModel,
)
from user.serializers import (
UserSerializer,
)
class UserView(APIView):
# permission_classes = [permissions.AllowAny]
def get(self, request):
user = request.user
return Response(UserSerializer(user).data)
# ํ์๊ฐ์
def post(self, request):
username = request.data.get("username")
password = request.data.pop("password")
password2 = request.data.pop("password2")
if password == password2:
user = UserModel(**request.data)
user.set_password(password)
user.save()
return Response({"message": "ํ์๊ฐ์
์๋ฃ!!"}, status=status.HTTP_200_OK)
elif UserModel.objects.get(username=username):
return Response({"message":"์ค๋ณต๋ ์์ด๋์
๋๋ค."}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
else:
return Response({"error": "๋น๋ฐ๋ฒํธ๊ฐ ์ผ์นํ์ง ์์ต๋๋ค."})
def put(self, request):
user = UserModel.objects.get(username=request.user)
if UserModel.objects.filter(nickname=request.data.get("nickname")) == True :
return Response({"error":"์ค๋ณต๋ ๋๋ค์์
๋๋ค."})
else:
pass
password = request.data.pop("password")
user.password = ""
user.set_password(password)
user_serializer = UserSerializer(user, data=request.data, partial=True, context={"request": request})
if user_serializer.is_valid():
user_serializer.save()
return Response(user_serializer.data, status=status.HTTP_200_OK)
return Response(user_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# original_username = request.user
# username = request.data.get("username")
# password = request.data.pop("password")
# nickname = request.data.get("nickname")
# gender = request.data.get("gender")
# user = UserModel(**request.data)
# user.set_password(password)
# return Response({'message': 'put method!!'})
def delete(self, request):
return Response({'message': 'delete method!!'})
class UserApiView(APIView):
# permission_classes = [permissions.AllowAny]
# ๋ก๊ทธ์ธ
def post(self, request):
username = request.data.get('username', '')
password = request.data.get('password', '')
user = authenticate(request, username=username, password=password)
if not user:
return Response({"error": "์กด์ฌํ์ง ์๋ ๊ณ์ ์ด๊ฑฐ๋ ํจ์ค์๋๊ฐ ์ผ์นํ์ง ์์ต๋๋ค."}, status=status.HTTP_401_UNAUTHORIZED)
else:
login(request, user)
return Response({"message": "๋ก๊ทธ์ธ ์ฑ๊ณต!!"}, status=status.HTTP_200_OK)
# ๋ก๊ทธ์์
def delete(self, request):
logout(request)
return Response({"message": "๋ก๊ทธ์์ ์ฑ๊ณต!!"}, status=status.HTTP_200_OK)
# jwt ํ ํฐ
class TokenObtainPairView(TokenObtainPairView):
serializer_class = TokenObtainPairSerializer
# ์ธ๊ฐ๋ ์ฌ์ฉ์๋ง ์ ๊ทผํ ์ ์๋ View ์์ฑ
class OnlyAuthenticatedUserView(APIView):
permission_classes = [permissions.IsAuthenticated]
# JWT ์ธ์ฆ๋ฐฉ์ ํด๋์ค ์ง์ ํ๊ธฐ
authentication_classes = [JWTAuthentication]
def get(self, request):
user = request.user
print(f"user ์ ๋ณด : {user}")
if not user:
return Response({"error": "์ ๊ทผ ๊ถํ์ด ์์ต๋๋ค."}, status=status.HTTP_401_UNAUTHORIZED)
return Response(UserSerializer(user).data)