๐Ÿ“’ [ TIL ] 2022.07.26_69์ผ์ฐจ # ์ตœ์ข… ํ”„๋กœ์ ํŠธ (11)

๋ฌธ๋ช…์ฃผยท2022๋…„ 7์›” 27์ผ
1
post-thumbnail

[ 2022-07-26 (ํ™”) ์˜ค๋Š˜์˜ TIL ]

[ Today Project ]

drf ๋ฐฑ์—”๋“œ๊ฐœ๋ฐœ + ํ”„๋ก ํŠธ๊ฐœ๋ฐœ
: ์ด๋ฒˆ ํ”„๋กœ์ ํŠธ๋Š” ํŒ€ํ”„๋กœ์ ํŠธ๋กœ ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค.

[ Today Learn ]

  • ๋งˆ์ดํŽ˜์ด์ง€ ์˜ค๋ฅ˜ ์ˆ˜์ •
  • ์•„์ด๋”” ๋ฐ ๋ชจ๋‹ฌ์ฐฝ ํ™œ๋™ ๋‹‰๋„ค์ž„์œผ๋กœ ๋ณ€๊ฒฝ

โœ๏ธ ๋‚ด๊ฐ€ ๋ฐฐ์šด๊ฒƒ, ์–ป์€๊ฒƒ

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)
        
profile
ํ•˜๋ฃจ ํ•œ๊ฑธ์Œ์”ฉ ๊พธ์ค€ํžˆ ๋‚˜์•„๊ฐ€๋Š” ๊ฐœ๋ฐœ์ž๐Ÿ™†โ€โ™€๏ธ https://github.com/Moonmooj

0๊ฐœ์˜ ๋Œ“๊ธ€

๊ด€๋ จ ์ฑ„์šฉ ์ •๋ณด