The issue must be in you authentication_classes
--(DRF doc) attribute (or DEFAULT_AUTHENTICATION_CLASSES
settings -- (DRF doc))
Behind the scenes, the DRF authentication classes fetch the auth user from the database and assign it to the request
object only after the specified request entity (like Token, JWT Token
, CSRF Token
, etc) validated against the database. This validation and assigning process is happening in the authentication classes.
Suppose, if Django or DRF failed to identify the requested user, it will assign the AnonymousUser
--(Django doc) object to the request
.
Fortunately, the AnonymousUser
object does have a groups
and user_permissions
attributes. Which means, neither request.user.groups
nor request.user.user_permissions
will not raise any AttributeError
exceptions.
Coming to your case, the request.user.groups
raised an exception, which indicates
- the received
User
object is neither settings.AUTH_USER_MODEL
nor AnonymousUser
- the
MyEndpoint
is missing a authentication_classes
attributes, hence DRF uses the DEFAULT_AUTHENTICATION_CLASSES
, which may contain a custom class, which may not built properly
Solution
I assume you need to use the token-based auth system, so I am using the DRF's TokenAuthentication
-- (DRF doc) here.
Assigning authentication_classes = (TokenAuthentication,)
in the view class will definitely sets the request.user
to either settings.AUTH_USER_MODEL
instance or AnonymousUser
.
from rest_framework.authentication import TokenAuthentication
class MyEndpoint(
mixins.ListModelMixin,
viewsets.GenericViewSet
):
permission_classes = [IsAuthenticated, ReadPermission]
http_method_names = ['get']
authentication_classes = (TokenAuthentication,)
Note
The issue does not belong to the permission_classes
settings, but the authentication_classes
Still not solved??
- Is it reproducible? (your code snippet is working nicely in my machine, probably everyone's machine) If so, add the steps to reproduce
- What is the value of
MIDDLEWARE
? Do you have any custom one?
- What is the value of
UNAUTHENTICATED_USER
?