Skip to content
Advertisement

Why doesn’t my request.user have groups in Django?

I’ve got an endpoint built with Django Rest Framework, to which I now want to add permissions so that only users belonging to a certain group can access an endpoint. So I’m using token based access and inspired by this example I’m trying to use the following code:

class ReadPermission(BasePermission):
    def has_permission(self, request, view):
        return request.user.groups.filter(name=settings.GROUP_POST_DATA).exists()

class MyEndpoint(mixins.ListModelMixin, viewsets.GenericViewSet):
    permission_classes = [IsAuthenticated, ReadPermission]
    http_method_names = ['get']
    # etc

But unfortunately I get anAttributeError: 'User' object has no attribute 'groups'

Why doesn’t the user object have groups?

Advertisement

Answer

Seems like you’re not using or inheriting from the default Django User model (or the AbstractUser) from django.contrib.auth.models, which have the ManyToMany relationship to Groups.

If you’re using some custom User model you can simply add the PermissionsMixin from the aforementioned module to inheritance (see docs). And also make sure that django.contrib.auth is in your INSTALLED_APPS setting.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement