Search code examples
djangodjango-rest-frameworkdjango-formsdjango-urlsdjango-rest-viewsets

AttributeError: 'function' object has no attribute 'get_extra_actions' in function view


views.py

@api_view(['GET', 'POST'])
def poll(request):
    if request.method == "GET":
        question = Question.objects.all()
        serializer = QuestionSerializer(question, many=True)
        return JsonResponse(serializer.data, safe=False)
    elif request.method == "POST":
        data = JsonParser.parse(request.POST)
        serializer = QuestionSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=201)
        return JsonResponse(serializer.errors, status=400)

api_urls.py

from django.contrib import admin
from django.urls import path, include
from . import views
from rest_framework import routers


router = routers.DefaultRouter()
router.register(r'poll', views.poll, basename='poll')

urlpatterns = [
    path('poll/', include(router.urls)),
]

error

 File "C:\Users\azhar\.virtualenvs\Django_and_Rest-YRrszWnq\lib\site-packages\rest_framework\routers.py", line 152, in get_routes
    extra_actions = viewset.get_extra_actions()
AttributeError: 'function' object has no attribute 'get_extra_actions'

many solution available for how to use get_extra_actions in class View but I want to use it in poll function please help me out


Solution

  • poll is a function based view, not a viewset. So you can't register it to a router. You can directly use it in the view:

    urlpatterns = [
        path('poll/', views.poll),
    ]