AttributeError: 'function' object has no attribute 'get_extra_actions' in function view
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)),
]
错误
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
poll
是一个 function based view
, not a viewset
。所以你不能把它注册到路由器上。可以直接在视图中使用:
urlpatterns = [
path('poll/', views.poll),
]
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)),
]
错误
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
poll
是一个 function based view
, not a viewset
。所以你不能把它注册到路由器上。可以直接在视图中使用:
urlpatterns = [
path('poll/', views.poll),
]