diff --git a/rest_framework/authtoken/management/commands/drf_create_token.py b/rest_framework/authtoken/management/commands/drf_create_token.py index ccd400ed5..8419614de 100644 --- a/rest_framework/authtoken/management/commands/drf_create_token.py +++ b/rest_framework/authtoken/management/commands/drf_create_token.py @@ -16,5 +16,11 @@ class Command(BaseCommand): def handle(self, *args, **options): username = options['username'] - token = self.create_user_token(username) + + try: + token = self.create_user_token(username) + except User.DoesNotExist: + print('Cannot create the Token: user {0} does not exist'.format( + username + )) print('Generated token {0} for user {1}'.format(token.key, username)) diff --git a/tests/test_authtoken.py b/tests/test_authtoken.py index 3b5a618e3..407d82944 100644 --- a/tests/test_authtoken.py +++ b/tests/test_authtoken.py @@ -48,3 +48,7 @@ class AuthTokenCommandTests(TestCase): assert token is not None token_saved = Token.objects.first() assert token.key == token_saved.key + + def test_command_create_user_token_invalid_user(self): + with pytest.raises(User.DoesNotExist): + AuthTokenCommand().create_user_token('not_existing_user')