alimp5

Custom Perm + BookDetail View (view method)

May 13th, 2021
879
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class SessionCsrfExemptAuthentication (SessionAuthentication):
  2.     def enforce_csrf(self, request):
  3.         pass
  4. class IsAuthenticatedAndOwner (permissions.BasePermission):
  5.     def has_permission(self, request, view):
  6.         return request.user and request.user.is_authenticated
  7.    
  8.     def has_object_permission(self, request, view, obj):
  9.         return obj.creator == request.user
  10.  
  11.  
  12. @api_view (['GET', 'PUT', 'DELETE'])
  13. @authentication_classes([drf_perms.SessionCsrfExemptAuthentication]) ##disable CSRF check.
  14. @permission_classes([drf_perms.IsAuthenticatedAndOwner])
  15. def book_detail (request, id):
  16.     book = get_object_or_404 (Book, id=id)
  17.     if request.method == 'GET':
  18.             serializer = BookSerializer(book)
  19.             return Response (serializer.data)
  20.  
  21.     elif request.method == 'PUT':
  22.         serializer = BookSerializer (book, data=request.data, context={'request': request})
  23.         if serializer.is_valid():
  24.             serializer.save()
  25.             return Response (serializer.data)
  26.         return Response (serializer.errors, status=status.HTTP_400_BAD_REQUEST)
  27.  
  28.     elif request.method == 'DELETE':
  29.         book.delete()
  30.         return Response (status=status.HTTP_204_NO_CONTENT)
RAW Paste Data