from rest_framework import serializers
from articles.models import Article
class ArticleSerializer(serializers.ModelSerializer):
user = serializers.SerializerMethodField()
def get_user(self, obj):
return obj.user.email
class Meta:
model = Article
fields = '__all__'
class ArticleCreateSerializer(serializers.ModelSerializer):
class Meta:
model = Article
fields = ("title", "image", "content")
class ArticleListSerializer(serializers.ModelSerializer):
user = serializers.SerializerMethodField()
def get_user(self, obj):
return obj.user.email
class Meta:
model = Article
fields = ("pk", "title", "image", "updated_at", "user")
from rest_framework.generics import get_object_or_404
from rest_framework.views import APIView
from rest_framework import status, permissions
from rest_framework.response import Response
from articles.models import Article
from articles.serializers import ArticleSerializer, ArticleListSerializer, ArticleCreateSerializer
class ArticleView(APIView):
def get(self, request):
articles = Article.objects.all()
serializer = ArticleListSerializer(articles, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
def post(self, request):
serializer = ArticleCreateSerializer(data=request.data)
if serializer.is_valid():
serializer.save(user=request.user)
return Response(serializer.data)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class ArticleDetailView(APIView):
def get(self, request, article_id):
article = get_object_or_404(Article, id=article_id)
serializer = ArticleSerializer(article)
return Response(serializer.data, status=status.HTTP_200_OK)
def put(self, request, article_id):
article = get_object_or_404(Article, id=article_id)
if request.user == article.user:
serializer = ArticleCreateSerializer(article, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_200_OK)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
else:
return Response("권한이 없습니다.", status=status.HTTP_403_FORBIDDEN)
def delete(self, request, article_id):
article = get_object_or_404(Article, id=article_id)
if request.user == article.user:
article.delete()
return Response("삭제되었습니다.", status=status.HTTP_204_NO_CONTENT)
else:
return Response("권한이 없습니다.", status=status.HTTP_403_FORBIDDEN)
수정 권한 테스트하기
- login API에서 다른 id로 로그인하기
- 받은 access token을 Environments > local > token에 업데이트 (2칸 모두) > 저장
- article update에서 수정해보면...
"권한이 없습니다." msg가 뜬다.