Reputation: 285
I am writing custom permission and inheriting in the generic views but it is not working it returns
TypeError: Cannot cast AnonymousUser to int. Are you trying to use it in place of User?
instead of User required to perform this action
my custom permission as follow
class IsOwnedByUser(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
message = {'detail': 'User required to perform this action'}
return obj.user == request.user
views.py
class OrderAddressView(generics.ListCreateAPIView):
queryset = OrderAddress.objects.all()
serializer_class = OrderAddressSerializer
permission_classes = (IsOwnedByUser,)
def perform_create(self, serializer):
serializer.save(user=self.request.user)
def get_queryset(self):
return OrderAddress.objects.filter(user=self.request.user)
BTW, it works fine with default rest framework permission class when I use like this
permission_class = (permissions.IsAuthenticated,)
but with my custom permission it is not working( Can anyone tell why it is that? Thanks in advance!
Upvotes: 2
Views: 1083
Reputation: 2518
You can also add a default in your settings.py file. Try with the following (adjust the permissions as you want though as in docs):
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated'
]
}
Upvotes: 0
Reputation: 1520
Actually, as Pavan Kumar told you, you should use both (permissions.IsAuthenticated, IsOwnedByUser) But if you want to use only one permission, you can create your own:
class IsAuthenticatedAndOwner(permissions.BasePermission):
message = 'User required to perform this action'
def has_permission(self, request, view):
return request.user and request.user.is_authenticated
def has_object_permission(self, request, view, obj):
return obj.user == request.user
Upvotes: 2