Ok, I found a way to get the auth token using email or username ... This is the serializer:
class AuthCustomTokenSerializer(serializers.Serializer): email_or_username = serializers.CharField() password = serializers.CharField() def validate(self, attrs): email_or_username = attrs.get('email_or_username') password = attrs.get('password') if email_or_username and password:
In the email_or_username field, the user can send an email or username and use the validateEmail () function, we can check whether the user is trying to log in using the email or username. Then we can make a request to get the user instance, if valid, and authenticate it.
This is a view.
class ObtainAuthToken(APIView): throttle_classes = () permission_classes = () parser_classes = ( parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser, ) renderer_classes = (renderers.JSONRenderer,) def post(self, request): serializer = AuthCustomTokenSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) content = { 'token': unicode(token.key), } return Response(content)
and then:
curl --data "email_or_username=emailorusername&password=password" http://127.0.0.1:8000/api/my-api-token-auth/.
Done.
source share