from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.generics import get_object_or_404
from community.models import Article
from community.serializers import ArticleSerializer
class ArticleList(APIView):
def get(self, request, format=None):
articles = Article.objects.all()
serializer = ArticleSerializer(articles, many=True)
return Response(serializer.data)
def post(self, request, format=None):
serializer = ArticleSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
print(serializer.errors)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class ArticleDetail(APIView):
# 상세 페이지 불러오기
def get(self, request, article_id, format=None):
article = get_object_or_404(Article, article_id=article_id)
serializer = ArticleSerializer(article)
return Response(serializer.data)
def put(self, request, article_id, format=None):
article = get_object_or_404(Article, article_id=article_id)
serializer = ArticleSerializer(article, data=request.data) # (기존 데이터, 변경할 데이터)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
def delete(self, request, article_id, format=None):
article = get_object_or_404(Article, article_id=article_id)
article.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
urlpatterns = [
path('', views.ArticleList.as_view(), name='article_list'),
path('<int:article_id>/', views.ArticleDetail.as_view(), name='article_detail'),
]