serializers.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334
  1. from django.contrib.auth import authenticate
  2. from django.utils.translation import gettext_lazy as _
  3. from rest_framework import serializers
  4. class AuthTokenSerializer(serializers.Serializer):
  5. username = serializers.CharField(label=_("Username"))
  6. password = serializers.CharField(
  7. label=_("Password"),
  8. style={'input_type': 'password'},
  9. trim_whitespace=False
  10. )
  11. def validate(self, attrs):
  12. username = attrs.get('username')
  13. password = attrs.get('password')
  14. if username and password:
  15. user = authenticate(request=self.context.get('request'),
  16. username=username, password=password)
  17. # The authenticate call simply returns None for is_active=False
  18. # users. (Assuming the default ModelBackend authentication
  19. # backend.)
  20. if not user:
  21. msg = _('Unable to log in with provided credentials.')
  22. raise serializers.ValidationError(msg, code='authorization')
  23. else:
  24. msg = _('Must include "username" and "password".')
  25. raise serializers.ValidationError(msg, code='authorization')
  26. attrs['user'] = user
  27. return attrs