Home > Back-end >  Getting all users from a Group - Django
Getting all users from a Group - Django

Time:12-29

I am trying to get the list of all users from the group "Manager", the post request works

  @api_view(['GET','POST'])    
  def managers(request):      
     username = request.data['username']
     if username:
          user = get_object_or_404(User, username=username)
          managers = Group.objects.get(name="Manager")
          if request.method == 'POST':
                managers.user_set.add(user)
          elif request.method == 'DELETE':
                managers.user_set.remove(user)
          return Response({"message": "ok"})
     
     return Response({"message": "error"}, status.HTTP_400_BAD_REQUEST)

I got this error below.

KeyError at /api/groups/manager/users 'username'

Please, can I get a guide?

CodePudding user response:

In case it is a GET request, you can work with:

@api_view(['GET', 'POST', 'DELETE'])
def managers(request):
    if request.method == 'GET':
        users = User.objects.filter(groups__name='Manager')
        serializer = UserSerializer(users, many=True)
        return Response({'data': serializer.data})
    username = request.data['username']
    if username:
        user = get_object_or_404(User, username=username)
        managers = Group.objects.get(name='Manager')
        if request.method == 'POST':
            managers.user_set.add(user)
        elif request.method == 'DELETE':
            managers.user_set.remove(user)
        return Response({"message": 'ok'})

    return Response({'message': 'error'}, status.HTTP_400_BAD_REQUEST)

With UserSerializer a ModelSerializer for the User model.

CodePudding user response:

For the benefit of others. Thank you Willem Van Onsem

users = User.objects.filter(groups__name='Manager')

  • Related