Django rest framework 'NoneType' object is not callable

I am new to django and drf. I've created a viewset for getting list of elements, adding new, updating and deleting, but I have some troubles when I try to create a viewset for getting detailed info about 1 element.

Here is my urls.py

urlpatterns = [
    path('tasks', views.TaskViewset.as_view(
        {
            'get':'list',
            'post':'add',
            'put':'update',
            'delete':'delete'
        }
    )),
    path('tasks/<int:pk>', views.TaskDetailViewset.as_view(
        {
            'get':'detail'
        }
    ))
]

and here is my TaskDetailViewset from views.py

class TaskDetailViewset(viewsets.ViewSet):

    def detail(self, request, pk, *args, **kwargs):
        #data = request.query_params
        task = models.Task.objects.get(id=pk)
        serializer = serializers.TaskSerializer(task)

        if serializer.is_valid():
            return Response(data=serializer.data, status=status.HTTP_200_OK)
        return Response(status=status.HTTP_404_NOT_FOUND)

When I try to send request to http://127.0.0.1:8000/api/v1/tasks/1 I get 'NoneType' object is not callable and I don't understand where is the problem here

Traceback:

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/api/v1/tasks/1

Django Version: 4.1.2
Python Version: 3.10.0
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'rest_framework',
 'todo']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback (most recent call last):
  File "/Users/aleksandr/Documents/projects/todoist/venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
  File "/Users/aleksandr/Documents/projects/todoist/venv/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/aleksandr/Documents/projects/todoist/venv/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/Users/aleksandr/Documents/projects/todoist/venv/lib/python3.10/site-packages/rest_framework/viewsets.py", line 125, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Users/aleksandr/Documents/projects/todoist/venv/lib/python3.10/site-packages/rest_framework/views.py", line 509, in dispatch
    response = self.handle_exception(exc)
  File "/Users/aleksandr/Documents/projects/todoist/venv/lib/python3.10/site-packages/rest_framework/views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/Users/aleksandr/Documents/projects/todoist/venv/lib/python3.10/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
    raise exc
  File "/Users/aleksandr/Documents/projects/todoist/venv/lib/python3.10/site-packages/rest_framework/views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)

Exception Type: TypeError at /api/v1/tasks/1
Exception Value: 'NoneType' object is not callable

in last return add this:

return Response(serializer.errors, status=status.HTTP_404_NOT_FOUND)

I think this problem is related to this line of your View:

if serializer.is_valid():

Maybe serializer or task is None so you get this error. I suggest you change detail method of `` like and see what would happen:

    def detail(self, request, pk=None):
        queryset = models.Task.objects.all()
        task = get_object_or_404(queryset, pk=pk)
        serializer = serializers.TaskSerializer(user)
        return Response(serializer.data)

Don't forget to import get_object_or_404 from django.shortcuts.

I found a reason of my problem but still don't get how it works. The problem was in th name of my method detail. When I changed name to details everything started to work fine.

Now my urls.py looks like this

urlpatterns = [
    path('tasks', views.TaskViewset.as_view(
        {
            'get':'list',
            'post':'add',
            'put':'update',
            'delete':'delete'
        }
    )),
    path('tasks/<int:pk>', views.TaskDetailViewset.as_view(
        {
            'get': 'details'
            }
    ))
]

My TaskDetailViewset looks like this:

class TaskDetailViewset(viewsets.ViewSet):

    def details(self, request, pk):
        task = models.Task.objects.get(id=pk)
        serializer = serializers.TaskSerializer(data=task.__dict__)

        if serializer.is_valid():
            return Response(data=serializer.data, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_404_NOT_FOUND)

Thank you all for helping me!

Back to Top