drf를 사용해서 CRUD 구현

permission_classes = [IsAuthenticated] 대신 사용 가능한것
인증된 사용자에게만 허용되는 것
1self.permission_classes = [IsAuthenticated]
이걸 쓰면 이 부분만 허용된다.
2
permission_classes = [IsAuthenticatedOrReadOnly]
이 권한은 API에서 익명 사용자에게 읽기 권한을 허용하고 인증된 사용자에게 쓰기 권한만 허용하려는 경우에 적합하다.
즉 「IsAuthenticatedOrReadOnly」을 써주면 get은 할 수 있으며
post, put, delete의 관계없이 전부다 인증 된 사용자에게만 액세스를 허용한다.
models.py
from django.conf import settings
from django.db import models
from accounts.models import User
class Product(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=120)
content = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
# author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
image = models.ImageField()
def __str__(self):
return str(self.title)
urls.py
from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', views.ProductView.as_view(), name='products'),
path('<int:pk>/', views.ProductDetailAPIView.as_view(), name='update'),
]
+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
views.py
from django.shortcuts import get_object_or_404, render
from rest_framework.views import APIView
from products.models import Product
from products.serializers import ProductSerializer
from rest_framework.response import Response
from rest_framework import status
from rest_framework.permissions import IsAuthenticated, IsAuthenticatedOrReadOnly
# 상품 등록, 목록 조회
class ProductView(APIView):
permission_classes = [IsAuthenticatedOrReadOnly]
# 상품 등록 이미지 업로드 질문
def get(self, request):
products = Product.objects.all()
serializer = ProductSerializer(products, many=True)
return Response(serializer.data)
def post(self, request):
self.permission_classes = [IsAuthenticated]
serializer = ProductSerializer(data=request.data)
if serializer.is_valid(raise_exception=True):
serializer.save()
return Response(serializer.data,status=status.HTTP_201_CREATED)
# 상품 수정, 삭제
class ProductDetailAPIView(APIView):
permission_classes = [IsAuthenticated]
def get_object(self, pk):
return get_object_or_404(Product, pk=pk)
def put(self, request, pk):
products = self.get_object(pk)
serializer = ProductSerializer(products, data=request.data, partial=True) # partial 부분적 수정을 가능하게 해준다.
if serializer.is_valid(raise_exception=True):
serializer.save()
return Response(serializer.data)
def delete(self, request, pk):
product = self.get_object(pk)
product.delete()
return Response(status=status.HTTP_200_OK)
POSTMAN
게시글 등록
pk값으로 받아올 때

상품 목록 조회

게시글 수정

게시글 삭제





