I am trying to make the PUT and DELETE methods require authentication but I want the GET method to be public. I know I can take the GET method out and put it into its own function but I would need to make another url for it. What would be the best way to approach this? thanks
@api_view(['GET', 'PUT', 'DELETE'])
@permission_classes([IsAuthenticated])
def getOrUpdateOrDeleteCar(request, pk):
if request.method == 'GET':
vehicle = Car.objects.get(id=pk)
serializer = CarSerializer(vehicle, many=False)
return Response(serializer.data)
elif request.method == 'PUT':
data = request.data
car = Car.objects.get(id=pk)
car.image=data['image']
car.make=data['make']
car.prototype=data['prototype']
car.year=data['year']
car.serviceInterval=data['serviceInterval']
car.seats=data['seats']
car.color=data['color']
car.vin=data['vin']
car.currentMileage=data['currentMileage']
car.save()
serializer = CarSerializer(car, many=False)
return Response(serializer.data)
elif request.method == 'DELETE':
car = Car.objects.get(id=pk)
car.delete()
return Response('Car Deleted!')
CodePudding user response:
Write a custom permission class:
from rest_framework.permissions import BasePermission
class CarPermission(BasePermission):
def has_permission(self, request, view):
if request.method == 'GET':
return True
return bool(request.user and request.user.is_authenticated)
And use it in your API:
@api_view(['GET', 'PUT', 'DELETE'])
@permission_classes([CarPermission])
def getOrUpdateOrDeleteCar(request, pk):
...