Json.loads (request.body) gives & ldquo; No JSON object can be decoded & rdquo; Error (Django)

advertisements

I am building an app using Django with Django Rest Framework and AngularJS with CoffeScript. I am basing on the tutorial https://thinkster.io/brewer/angular-django-tutorial/. I have a problem with passing json from the client side, but I think that the problem is clearly in my view, because even posting json via DRF api gives the same error - "No JSON object could be decoded" caused by the line data = json.loads(request.body).

My APIView is following (clearly the same as in the tutorial):

class LoginView(views.APIView):

    def post(self, request, format=None):
        data = json.loads(request.body)

        email = data.get('email', None)
        password = data.get('password', None)

        account = authenticate(email=email, password=password)

        if account is not None:
            if account.is_active:
                login(request, account)

                serialized = AccountSerializer(account)

                return Response(serialized.data)
            else:
                return Response({
                    'status': 'Unathorized',
                    'message': 'This account has been disabled.'
                }, status=status.HTTP_401_UNATHORIZED)
        else:
            return Response({
                'status': 'Unathorized',
                'message': 'Username/password combination invalid.'
            }, status=status.HTTP_401_UNATHORIZED)

When I try to pass the JSON from api and try to print request.body in the console I have such a result:

csrfmiddlewaretoken=s2dIiOy7eNUJJfGBRaDAFmJ632kjbokz&_content_type=application%2Fjson&_content=%7B%0D%0A%22email%22%3A+%[email protected]%22%2C%0D%0A%22password%22%3A+%22example%22%0D%0A%7

It doesn't seem to be a correct JSON. Am I right that something is wrong in this view? Or should I look somewhere else?


I had the same issue.

    email = request.data.get('email', None)
    password = request.data.get('password', None)

This solved my problem.