Skip to content
Advertisement

Post successful but response is an error on front end

I am posting data through 127.0.0.8000/post/. My post is of course successful cause I am able to see what I posted in the base URL of 127.0.0.8000 successfully but I get the following response on the Django front end.

AssertionError at /post/
Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>`

In VS Code I get the following errors in terminal

Internal Server Error: /post/
Traceback (most recent call last):
  File "C:UsersAhmedAppDataLocalProgramsPythonPython310libsite-packagesdjangocorehandlersexception.py", line 47, in inner
    response = get_response(request)
  File "C:UsersAhmedAppDataLocalProgramsPythonPython310libsite-packagesdjangocorehandlersbase.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:UsersAhmedAppDataLocalProgramsPythonPython310libsite-packagesdjangoviewsdecoratorscsrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "C:UsersAhmedAppDataLocalProgramsPythonPython310libsite-packagesdjangoviewsgenericbase.py", line 69, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:UsersAhmedAppDataLocalProgramsPythonPython310libsite-packagesrest_frameworkviews.py", line 511, in dispatch
    self.response = self.finalize_response(request, response, *args, **kwargs)
  File "C:UsersAhmedAppDataLocalProgramsPythonPython310libsite-packagesrest_frameworkviews.py", line 423, in finalize_response
    assert isinstance(response, HttpResponseBase), (
AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>`
[27/Feb/2022 16:22:13] "POST /post/ HTTP/1.1" 500 74030
[27/Feb/2022 16:22:24] "GET / HTTP/1.1" 200 5799

My Views.Py is the following

@api_view(['GET'])
def getData(request):
    queryset = Wallet.objects.all()
    serializer = WalletSerializer(queryset, many=True, context={'request': request})
    return Response(serializer.data)

@api_view(['GET'])
def getSingleData(request,pk):
    queryset = Wallet.objects.all(id=pk)
    serializer = WalletSerializer(queryset, many=False)
    return Response(serializer.data)

@api_view(['POST'])
def postData(request):
    serializer = WalletSerializer(data = request.data)
    if serializer.is_valid():
        serializer.save()

P.S I am also unable to GET individual data through ID in the second method, it doesn’t work

Advertisement

Answer

You should return a response instance from your view/API

@api_view(['POST'])
def postData(request):
    serializer = WalletSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data)
    return Response(serializer.errors)
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement