Skip to content

Instantly share code, notes, and snippets.

@dustinfarris
Last active December 28, 2015 08:29
Show Gist options
  • Save dustinfarris/7471573 to your computer and use it in GitHub Desktop.
Save dustinfarris/7471573 to your computer and use it in GitHub Desktop.
Django + DRF, Using an email address as a username
class User(AbstractUser):
pass
class UserSerializer(serializers.ModelSerializer):
username = serializers.EmailField()
class Meta:
model = User
def validate_username(self, attrs, source):
"""
Customize the error message for a duplicate username.
Use "email" instead of "username"
"""
if self.object is None:
username = attrs[source]
if User._default_manager.filter(username=username).exists():
raise serializers.ValidationError("That email is already being used.", code='duplicate_username')
return attrs
class UserViewSet(viewsets.ModelViewSet):
model = User
serializer_class = UserSerializer
def pre_save(self, obj):
obj.email = obj.username
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment