简体   繁体   中英

Assign permissions to user in Django

I'm using Django User model in my Django project. my user view is:

from django.contrib.auth.models import User
from django.dispatch import receiver
from django.db.models.signals import post_save

from rest_framework import generics
from rest_framework import permissions
from rest_framework import status
from rest_framework.authtoken.models import Token
from rest_framework.response import Response

from myapp.serializers.user import UserSerializer, UserListSerializer


class UserList(generics.ListCreateAPIView):
    model = User
    permission_classes = (permissions.IsAuthenticated, )
    _ignore_model_permissions = True
    serializer_class = UserListSerializer
    queryset = User.objects.exclude(pk=-1)

    def post(self, request, *args, **kwargs):
        userName = request.DATA.get('username', None)
        userPass = request.DATA.get('password', None)
        user = User.objects.create_user(username=userName, password=userPass)
        if not user:
            return Response({'message': "error creating user"}, status=status.HTTP_200_OK)
        return Response({'username': user.username}, status=status.HTTP_201_CREATED)


class UserDetail(generics.RetrieveUpdateDestroyAPIView):
    model = User
    permission_classes = (permissions.IsAuthenticated, )
    _ignore_model_permissions = True
    serializer_class = UserSerializer
    queryset = User.objects.exclude(pk=-1)

When I try to view users page logged in as a superuser, I can see the list of all the users. But when I try to access it with a non-superuser, I get an empty list. I like every user to be able to view the user list but only its own user detail if it is non superuser. I tried using signals (such as post_migrate ) but the problem is that for each user I need to give view permission to every other user every time I migrate.

Is there any easier way to do this?

I can see the list of all the users. But when I try to access it with a non-superuser, I get an empty list.

From your code you should be able to access UserList even if you are not superuser.

I like every user to be able to view the user list but only its own user detail if it is non superuser.

Try custom permission.

class IsOwner(permissions.BasePermission):
    """
    Custom permission to only allow owners of an object to edit it.
    """
    def has_object_permission(self, request, view, obj):
        return obj == request.user

class UserDetail(generics.RetrieveUpdateDestroyAPIView):
    model = User
    permission_classes = (permissions.IsOwner, )
    _ignore_model_permissions = True
    serializer_class = UserSerializer
    queryset = User.objects.exclude(pk=-1)

Now only owner can see their details

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM