Module 'rest_framework.request' has no attribute 'method' Django error

Viewed 587

I'm having a strange error and I didn't find answers nowhere and that's mean that I need your help(again).

So, I'm having two views in my views.py file and I'm trying to adding GET and POST methods for one view, I've tried to check the method with request. Method but rest frame work module tells me that has no that attribute, can you help me, please, with a fix for this issue? Thank you!

In models.py I have:

class ChatViewSet(ConversationViewSet):

    @api_view(['GET', 'POST'])
    def get_chat(self, **kwargs):

        if request.method == 'GET':
            information = Chat.objects.all()
            tutorials_serializer = ChatSerializer(information, many=True).data
            return JsonResponse(tutorials_serializer, safe=False)
        elif request.method == 'POST':
            tutorial_data = JSONParser().parse(request)
            tutorial_serializer = ChatSerializer(data=tutorial_data)
            tutorial_data['status'] = 'new'
            tutorial_data['chat_id'] += 1
            if tutorial_serializer.is_valid():
                tutorial_serializer.save()
                return JsonResponse(tutorial_serializer.data,
                                    status=status.HTTP_201_CREATED)
            return JsonResponse(tutorial_serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)

In urls.py:

urlpatterns = [

    url(r'^conversation/', ConversationViewSet.get_all),
    url(r'^conversation/(?P<pk>[0-9]+)$', ConversationViewSet.get_by_id),
    url(r'chat', ChatViewSet.get_chat),
]

And error:

if request.method == 'GET':
AttributeError: module 'rest_framework.request' has no attribute 'method'
2 Answers

Your function is inside a class which I assume from the name is a ViewSet that means you really don't need that api_view decorator. The api_view decorator is used to make an api view from a functional view and not with class based views. Instead with viewsets you want to use the action decorator to mark extra actions for routing:

from rest_framework.decorators import action


class ChatViewSet(ConversationViewSet):

    @action(detail=True, methods=['get', 'post'])
    def get_chat(self, **kwargs):
        ...

Add a staticmethod decorator and request in get_chat:

@api_view(['GET', 'POST'])
@staticmethod
def get_chat(request, **kwargs):
Related