2024-10-05 17:30:35 +02:00
|
|
|
# catalog/api_views.py
|
|
|
|
|
|
|
|
|
|
from rest_framework import generics
|
2024-12-22 03:07:07 +01:00
|
|
|
from rest_framework.parsers import MultiPartParser, FormParser, JSONParser
|
2024-10-05 17:30:35 +02:00
|
|
|
from rest_framework.filters import SearchFilter
|
2026-06-20 07:06:19 +02:00
|
|
|
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
|
2024-12-22 03:07:07 +01:00
|
|
|
|
|
|
|
|
from .permissions import IsAuthenticatedOrReadOnly
|
2026-06-20 07:06:19 +02:00
|
|
|
from .models import Plant, PlantImage
|
2024-10-05 17:30:35 +02:00
|
|
|
from .serializers import PlantSerializer
|
|
|
|
|
|
|
|
|
|
# List and Create Plants
|
|
|
|
|
class PlantListCreateAPIView(generics.ListCreateAPIView):
|
|
|
|
|
queryset = Plant.objects.all()
|
|
|
|
|
serializer_class = PlantSerializer
|
2024-12-22 03:07:07 +01:00
|
|
|
parser_classes = [JSONParser, MultiPartParser, FormParser] # Allow file uploads
|
2024-10-05 17:30:35 +02:00
|
|
|
filter_backends = [SearchFilter] # Add search filter
|
|
|
|
|
search_fields = ['name', 'description'] # Search by name and description
|
2024-12-22 03:07:07 +01:00
|
|
|
permission_classes = [IsAuthenticatedOrReadOnly] # Apply custom permission
|
|
|
|
|
|
2024-10-05 17:30:35 +02:00
|
|
|
# Retrieve, Update, and Delete a Plant
|
|
|
|
|
class PlantRetrieveUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView):
|
|
|
|
|
queryset = Plant.objects.all()
|
|
|
|
|
serializer_class = PlantSerializer
|
2024-12-22 03:07:07 +01:00
|
|
|
parser_classes = [JSONParser, MultiPartParser, FormParser] # Allow file uploads and form data
|
2026-06-20 07:06:19 +02:00
|
|
|
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)
|
|
|
|
|
|