I have two Blog API's in Django Rest Framework. One uses Django's default User model whilst the other uses a CustomUser. Authentication works well in both cases. I have similar serializers, viewsets and routers all configured. The endpoints that returns a collection of posts and users works well as well as the endpoint for a single post. Also that of a single user works only while using Django's default user model. However when I try to access a single CustomUser, I get this error:
AttributeError at /api/v1/users/3/
'CustomUser' object has no attribute 'author'
Request Method: GET
Request URL: http://127.0.0.1:3412/api/v1/users/3/
Django Version: 5.1.2
Exception Type: AttributeError
Exception Value: 'CustomUser' object has no attribute 'author'
Exception Location: C:\Users\Names\OneDrive\my_apps\django_apps\blog_API\api\permissions.py, line 16, in has_object_permission
Raised during: api.views.CustomUserViewSet
The exception occurs on the last line:
from rest_framework import permissions
class IsAuthorOrReadOnly(permissions.BasePermission):
"""
Object-level permission to only allow authors of an object to edit it.
Assumes the model instance has an `author` attribute.
"""
def has_object_permission(self, request, view, obj):
if request.method in permissions.SAFE_METHODS:
return True
return obj.author == request.user
Here's my CustomUserViewset:
from rest_framework import viewsets
from users.models import CustomUser
from .serializers import CustomUserSerializer
from .permissions import IsAuthorOrReadOnly
class CustomUserViewSet(viewsets.ModelViewSet):
"""Viewset for Custom User Object."""
queryset = CustomUser.objects.all()
serializer_class = CustomUserSerializer
permission_classes = (IsAuthorOrReadOnly,)
I have looked at the location of the error and tried print debugging to print the User object and in both cases (Default User model and CustomUser model), nothing gets printed. But Default User model works well and returns details of a single user. I also tried to print my queryset and it correctly returns my CustomUser.
I want to access a single CustomUser from the endpoint just like I can with Dango's default User. My Post
and CustomUser
models are correctly serialized and both collections can be seen from their endpoints. The PostDetail also works well. I'd be happy to provide more clarification if needed. Thanks...
Removing permission_classes = (IsAuthorOrReadOnly,)
from my CustomUserViewSet
fixed the issue.
Not sure why but I'm guessing the viewset wasn't happy with the repetition of permission_classes
in both PostViewSet and CustomUserViewSet.