Last active
December 28, 2015 08:29
-
-
Save dustinfarris/7471573 to your computer and use it in GitHub Desktop.
Django + DRF, Using an email address as a username
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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