Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Custom permissions for function based views

how can I write custom permissions for a function based view? I am using the REST framework, and I have written a ciphertext encryption/decryption API. I have one function based view for each key (key-detail) which I would like to only make available to the owner of that key. I know that when using class based views, it is enough to define permission_classes, but how do I do this for function based views? I have tried using the @permission_classes decorator, but it is not working for my custom permission, which is written as so:

class IsOwner(permissions.BasePermission):
    """
    Custom permission to only allow owners of an object to access it.
    """

    def has_object_permission(self, request, view, obj):
        return obj.owner == request.user
like image 354
b_pcakes Avatar asked Feb 20 '16 07:02

b_pcakes


People also ask

How do I use custom permissions in Django?

Django Admin Panel : In Admin Panel you will see Group in bold letter, Click on that and make 3-different group named level0, level1, level3 . Also, define the custom permissions according to the need. By Programmatically creating a group with permissions: Open python shell using python manage.py shell.

Does Django have view permissions?

The Django admin site uses permissions as follows: Access to view objects is limited to users with the “view” or “change” permission for that type of object. Access to view the “add” form and add an object is limited to users with the “add” permission for that type of object.

What is permissions Safe_methods?

SAFE_METHODS: # Check permissions for read-only request else: # Check permissions for write request. Note: The instance-level has_object_permission method will only be called if the view-level has_permission checks have already passed.

How do I add permissions to a Django model?

Add Permissions to a Group If you are using AbstractUser in Django, you must add AUTH_USER_MODEL = 'YourAppName. YourClassName' . This way, you are telling Django to use our custom user model instead of the default one. The code below should go in your admin.py file so that you can see your user model.


1 Answers

It seems like it's a known issue, has_object_permission is not supported when using function based views, it's reported here.

If you would like to call has_permission, you should be able to do so using the permission_classes decorator as shown in the documentation

@api_view(['GET'])
@permission_classes((IsAuthenticated, ))
def example_view(request, format=None):
    content = {
        'status': 'request was permitted'
    }
    return Response(content)
like image 158
Forge Avatar answered Sep 28 '22 05:09

Forge