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.
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
).