67 lines
2.9 KiB
Python
67 lines
2.9 KiB
Python
from django.core.paginator import Paginator
|
|
from rest_framework.views import APIView
|
|
from .models import *
|
|
from .serializers import *
|
|
from rest_framework import status
|
|
from rest_framework.response import Response
|
|
from django.db.models import Q
|
|
from django.shortcuts import get_object_or_404
|
|
from rest_framework.permissions import IsAuthenticatedOrReadOnly
|
|
from utils.pagination import StructurePagination
|
|
|
|
class AllCategories(APIView):
|
|
serializer_class = CategorySerializer
|
|
def get(self, request):
|
|
categories = CategoryModel.objects.all()
|
|
categories_ser = self.serializer_class(instance=categories, many=True)
|
|
return Response({"categories": categories_ser.data}, status=status.HTTP_200_OK)
|
|
|
|
class ProductView(APIView):
|
|
serializer_class = ProductModel
|
|
def get(self, request, pk):
|
|
product = get_object_or_404(ProductModel, id=pk)
|
|
product_ser = self.serializer_class(instance=product, many=False)
|
|
return Response({"product": product_ser.data}, status=status.HTTP_200_OK)
|
|
|
|
class AllProductsView(APIView):
|
|
serializer_class = ProductSerializer
|
|
pagination_class = StructurePagination
|
|
def get(self, request, pk):
|
|
try:
|
|
category = Category.objects.get(pk=pk)
|
|
products = Product.objects.filter(category__in=category.get_descendants(include_self=True))
|
|
paginator = self.pagination_class()
|
|
paginated_products = paginator.paginate_queryset(products, request)
|
|
serializer = self.serializer_class(paginated_products, many=True)
|
|
return paginator.get_paginated_response(serializer.data)
|
|
except Category.DoesNotExist:
|
|
return Response({"detail": "Category not found."}, status=status.HTTP_404_NOT_FOUND)
|
|
|
|
|
|
class CommentView(APIView):
|
|
serializer_class = CommentSerializer
|
|
permission_classes = [IsAuthenticatedOrReadOnly]
|
|
def get(self, request, pk):
|
|
product = get_object_or_404(ProductModel, id=pk)
|
|
comments = product.comments.filter(show=True)
|
|
comments_ser = self.serializer_class(instance=comments, many=True)
|
|
return Response({'comments': comments_ser.data}, status=status.HTTP_200_OK)
|
|
|
|
def post(self, request, pk):
|
|
comment_ser = CommentSerializer(data=request.data)
|
|
product = get_object_or_404(ProductModel, id=pk)
|
|
if comment_ser.is_valid():
|
|
comment_ser.save(product=product, user=request.user)
|
|
return Response(comment_ser.data, status=status.HTTP_201_CREATED)
|
|
return Response(comment_ser.errors, status=status.HTTP_400_BAD_REQUEST)
|
|
|
|
def delete(self, request, pk):
|
|
comment = get_object_or_404(CommentModel, pk=pk)
|
|
if comment.user == request.user:
|
|
comment.delete()
|
|
return Response(status=status.HTTP_204_NO_CONTENT)
|
|
else:
|
|
return Response({"detail": "شما اجازه ی پاک کردن این کامنت را ندارید"}, status=status.HTTP_403_FORBIDDEN)
|
|
|
|
|