title: Django REST Framework: force lowercase username
body: <p>I am just starting to play around with Django REST Framework for a side project, and I am trying to force all usernames to be lowercase (since by default they are case sensitive and I don't want people to have usernames like <code>kevin</code> and <code>Kevin</code> for example).</p>
  
  <p>This is the code I am using to create a user:</p>
  
  <pre class="lang-py prettyprint-override"><code># The serializer
  class UserSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True)
    token = serializers.SerializerMethodField()
  
    def create(self, validated_data):
      user = get_user_model().objects.create(**validated_data)
      user.set_password(validated_data['password'])
      user.save()
      return user
  
    def get_token(self, user):
      token = Token.objects.create(user=user)
      return token.key
  
    class Meta:
      model = get_user_model()
      fields = ('username', 'first_name', 'last_name', 'email', 'password', 'token')
  
  
  # The View
  class RegisterUserView(CreateAPIView):
    model = User
    serializer_class = UserSerializer
    permission_classes = (permissions.AllowAny, )
  
  
  # And the URL pattern
  urlpatterns = [
    path(r'user/register/', RegisterUserView.as_view()),
  ]
  </code></pre>
  
  <p>So the user can create a new account by posting at least a username and password to <code>user/register</code>, and in the response he'll get the full user object (with first name, last name, email and the auth token). This works.</p>
  
  <p>However, I am struggling with forcing lowercase usernames. For example when I add something like <code>validated_data['username'] = validated_data['username'].lower()</code> to the create function in the serializer, the server simply generates an error 500 "UNIQUE constraint failed: auth_user.username" when trying to create a user with the same username (but different case). That's of course not ideal, that error 500.</p>
  
  <p>I've found some suggestions to add a custom user manager, something like this:</p>
  
  <pre class="lang-py prettyprint-override"><code>lass MyUserManager(BaseUserManager):
      def get_by_natural_key(self, username):
          return self.get(username__iexact=username)
  </code></pre>
  
  <p>But that didn't do anything either, after hooking it up via a custom user class and adding to the settings file. I could still create users with capitals in their username. </p>
  
  <p>What's the simplest solution to get this to simply work?</p>