0

I'm using Django 2.x and django-oauth-toolkit to generate access token.

I have written a custom token view to run a few checks on the account and then generate access token to the user. If custom check fails, I want to raise an exception with 400 status code.

class CustomTokenView(TokenView):
    def create_token_response(self, request):
        login = request.POST.pop('username', None)

        username = get_user_model().objects.filter(
            email=login[0]
        ).last()

        if not username.verified:
            raise HttpResponse(content='User not verified', status=status.HTTP_400_BAD_REQUEST)

        request.POST._mutable = mutable

        return super(TokenView, self).create_token_response(request)

But this gives error as

TypeError: exceptions must derive from BaseException

I also tried with

from rest_framework.response import Response  
return Response('User not verified', status=status.HTTP_400_BAD_REQUEST)

But none is working.

Anuj TBE
  • 9,198
  • 27
  • 136
  • 285

1 Answers1

1

You cannot raise a response. Response is not an exception. Instead you can either return it or raise an actual exception from django-rest-framework (all available exceptions described here, select one that suits best your case. In my opinion it should be your custom one, created from APIException).

GwynBleidD
  • 20,081
  • 5
  • 46
  • 77
  • When I use `return` it gives `django.template.response.ContentNotRenderedError: The response content must be rendered before it can be iterated over.`. It seems it is calling the function from Base class `TokenView` on return. I'm returning error message whereas it expects request body with username and password parameters. – Anuj TBE Jan 27 '19 at 03:25