[Django]-How to make permission for groups and administrators

5👍

You’re looking for Django REST Framework’s Custom Permissions. You could also take a look at IsAdminUser IsAuthenticatedOrReadOnly for inspiration.

For example you could use:

from rest_framework import permissions

class IsAdminOrReadOnly(permissions.BasePermission):
    """Allow unsafe methods for admin users only."""

    def has_permission(self, request, view):
        if not request.user or not request.user.is_authenticated():
            return False
        if request.user.is_superuser:
            return True
        if request.method in permissions.SAFE_METHODS:
            return bool(Group.objects.get(name='Patient').
                        user_set.filter(id=request.user.id).exists())
        return False

You can also take a look ad DjangoModelPermissions.

Then it’s just a matter of using the new permission either on the whole API:

# in settings.py
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'myapp.permissions.IsAdminOrReadOnly',
    )
}

or on each view as needed.

1👍

For users in group called api_users you have:

class IsApiUser(BasePermission):
    #Allows access only to api_users group members.
    def has_permission(self, request, view):
        if request.user and request.user.groups.filter(name='api_users'):
            return True
        return False

next

class custListView(RetrieveAPIView):
    permission_classes = (IsApiUser,)
    serializer_class = custSerializer
    ...

hope it will help uyou

Leave a comment