40 lines
1.7 KiB
Python
Executable file
40 lines
1.7 KiB
Python
Executable file
# catalog/api_views.py
|
|
|
|
from rest_framework import generics
|
|
from rest_framework.parsers import MultiPartParser, FormParser, JSONParser
|
|
from rest_framework.filters import SearchFilter
|
|
from rest_framework.response import Response
|
|
from rest_framework import status
|
|
|
|
from rest_framework.views import APIView
|
|
from django.shortcuts import get_object_or_404
|
|
|
|
from .permissions import IsAuthenticatedOrReadOnly
|
|
from .models import Plant, PlantImage
|
|
from .serializers import PlantSerializer
|
|
|
|
# List and Create Plants
|
|
class PlantListCreateAPIView(generics.ListCreateAPIView):
|
|
queryset = Plant.objects.all()
|
|
serializer_class = PlantSerializer
|
|
parser_classes = [JSONParser, MultiPartParser, FormParser] # Allow file uploads
|
|
filter_backends = [SearchFilter] # Add search filter
|
|
search_fields = ['name', 'description'] # Search by name and description
|
|
permission_classes = [IsAuthenticatedOrReadOnly] # Apply custom permission
|
|
|
|
# Retrieve, Update, and Delete a Plant
|
|
class PlantRetrieveUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView):
|
|
queryset = Plant.objects.all()
|
|
serializer_class = PlantSerializer
|
|
parser_classes = [JSONParser, MultiPartParser, FormParser] # Allow file uploads and form data
|
|
permission_classes = [IsAuthenticatedOrReadOnly] # Apply custom permission
|
|
|
|
|
|
class PlantImageDeleteAPIView(APIView):
|
|
permission_classes = [IsAuthenticatedOrReadOnly] # Ensure only authenticated users can delete
|
|
|
|
def delete(self, request, image_id):
|
|
image = get_object_or_404(PlantImage, id=image_id)
|
|
image.delete() # Delete the image object from the database
|
|
return Response({"message": "Image deleted successfully"}, status=status.HTTP_204_NO_CONTENT)
|
|
|