title: Test creation of a custom user using DRF
body: <p>The goal is to test creating a new custom user using <a href="https://www.django-rest-framework.org/api-guide/testing/#api-test-cases" rel="nofollow noreferrer">APITestCase</a>.</p>
  
  <p>In models.py got two new classes inheriting from <a href="https://docs.djangoproject.com/en/3.0/topics/auth/customizing/#django.contrib.auth.models.AbstractBaseUser" rel="nofollow noreferrer">AbstractBaseUser</a> and <a href="https://docs.djangoproject.com/en/3.0/topics/auth/customizing/#django.contrib.auth.models.BaseUserManager" rel="nofollow noreferrer">BaseUserManager</a>, respectively</p>
  
  <pre><code>class MyUser(AbstractBaseUser):
      objects = MyUserManager()
      class Meta:
          db_table = 'user_entity'
  
      user_id = models.AutoField(primary_key=True)
      #username = models.CharField(max_length=USERNAME_MAX_LENGTH, unique=True, validators=[validators.validate_username])
      username = models.CharField(max_length=20, unique=True)
      password = models.CharField(max_length=256)
      first_name = models.CharField(max_length=25)
      last_name = models.CharField(max_length=25)
      email = models.EmailField(verbose_name='email', max_length=100, unique=True)
      last_access = models.DateField(default=datetime.date.today)
      creation_date = models.DateTimeField(default=timezone.now)
      last_update = models.DateField(default=datetime.date.today)
      user_type = models.IntegerField()
      is_staff = models.BooleanField(default=False)
      is_active = models.BooleanField(default=True)
  
      USERNAME_FIELD = 'email'
      EMAIL_FIELD = 'email'
      REQUIRED_FIELDS = ['username', 'first_name', 'last_name', 'user_type']
  
      def __str__(self):
          return str(self.user_id) + " (%s)" % str(self.email)
  
      def has_perm(self, perm, obj=None):
          return self.user_type == 0
  
      def has_module_perms(self, app_label):
          return True
  </code></pre>
  
  <p>and</p>
  
  <pre><code>class MyUserManager(BaseUserManager):
      def _create_generic_user(self, email, username, password, first_name, last_name, user_type):
          if not username:
              raise ValueError("Username cannot be empty")
          if not email:
              raise ValueError("Email cannot be empty")
          if not first_name:
              raise ValueError("First name cannot be empty")
          if not last_name:
              raise ValueError("Last name cannot be empty")
          if not password:
              raise ValueError("Password cannot be empty")
  
          user = self.model(
              username=username,
              first_name=first_name,
              last_name=last_name,
              email=self.normalize_email(email),
              user_type=user_type,
              is_staff=user_type == 0,
              is_active=False
          )
          user.set_password(password)
          user.save(user=self._db)
          return user
  
      def create_user(self, email, username, password, first_name, last_name):
          return self._create_generic_user(email, username, password, first_name, last_name, 2)
  
      def create_admin(self, email, username, password, first_name, last_name):
          return self._create_generic_user(email, username, password, first_name, last_name, 0)
  </code></pre>
  
  <p>Then, in serializers.py created a MyUserSerializer for DRF inheriting from a <a href="https://www.django-rest-framework.org/api-guide/serializers/#modelserializer" rel="nofollow noreferrer">ModelSerializer</a></p>
  
  <pre><code>class MyUserSerializer(serializers.ModelSerializer):
      email = serializers.EmailField(
              required=True, # make sure email is provided
              validators=[UniqueValidator(queryset=MyUser.objects.all())] # make sure email is unique
              )
      username = serializers.CharField(
              required=True,
              validators=[UniqueValidator(queryset=MyUser.objects.all())],
              min_length=5,
              max_length=20
              )
      password = serializers.CharField(
              write_only=True,
              required=True,
              max_length=256
              )
      first_name = serializers.CharField(
              required=True,
              max_length=25
              )
      last_name = serializers.CharField(
              required=True,
              max_length=25
              )
  
      def create(self, validated_data):
          user = MyUser.objects.create_user(validated_data['email'], validated_data['username'], validated_data['password'],
          validated_data['first_name'], validated_data['last_name'])
          return user
  
  
      class Meta:
          model = MyUser
          fields = ('user_id', 'email', 'username', 'password', 'first_name', 'last_name')
  </code></pre>
  
  <p>a view with APIView</p>
  
  <pre><code>class MyUserCreate(APIView):
      """ 
      Creates the user. 
      """
  
      def post(self, request, format='json'):
          serializer = MyUserSerializer(data=request.data)
          if serializer.is_valid():
              user = serializer.save()
              if user:
                  return Response(serializer.data, status=status.HTTP_201_CREATED)
  </code></pre>
  
  <p>and urls</p>
  
  <pre><code>urlpatterns = [
      url(r'api/users^$', views.MyUserCreate.as_view(), name='user-create'),
  ]
  </code></pre>
  
  <p>From this, then went on to create a simple test of creating users</p>
  
  <pre><code>class MyUserTest(APITestCase):
      def setUp(self):
          # Create a user
          self.test_user = MyUser.objects.create_user('tiagomartinsperes@gmail.com', 'tiagoperes', 'EWFdfew45te!sadf32', 'Tiago', 'Peres')
  
          # URL for creating user
          self.create_url = reverse('user-create')
  
      def test_create_user(self):
          """
          Ensure we can create a new user and a valid token is created with it.
          """
          data = {
              'email': 'cnf32344@zzrgg.com',
              'username': 'andresantos',
              'password': 'test',
              'first_name': 'André',
              'last_name': 'Santos'
          }
  
          response = self.client.post(self.create_url , data, format='json')
  
          # Make sure we have two users in the database
          self.assertEqual(MyUser.objects.count(), 2)
          # Return 201
          self.assertEqual(response.status_code, status.HTTP_201_CREATED)
          # Return the username and email upon successful creation
          self.assertEqual(response.data['email'], data['email'])
          self.assertEqual(response.data['username'], data['username'])
          self.assertFalse('password' in response.data)
          self.assertEqual(response.data['first_name'], data['first_name'])
          self.assertEqual(response.data['last_name'], data['last_name'])
  </code></pre>
  
  <p>Thing is, running</p>
  
  <pre><code>python manage.py test
  </code></pre>
  
  <p>gets the following error:</p>
  
  <blockquote>
    <p>Creating test database for alias 'default'... System check identified
    no issues (0 silenced). E
    ====================================================================== ERROR: test_create_user (user.tests.MyUserTest) Ensure we can create a
    new user and a valid token is created with it.
    ---------------------------------------------------------------------- Traceback (most recent call last):   File
    "C:\Users\tiago\Desktop\letsgo\COVID19-be\django_server\user\tests.py",
    line 10, in setUp
        self.test_user = MyUser.objects.create_user('tiagomartinsperes@gmail.com',
    'tiagoperes', 'EWFdfew45te!sadf32', 'Tiago', 'Peres')   File
    "C:\Users\tiago\Desktop\letsgo\COVID19-be\django_server\user\models.py",
    line 38, in create_user
        return self._create_generic_user(email, username, password, first_name, last_name, 2)   File
    "C:\Users\tiago\Desktop\letsgo\COVID19-be\django_server\user\models.py",
    line 34, in _create_generic_user
        user.save(user=self._db)   File "C:\Users\tiago\Desktop\letsgo\unstable\lib\site-packages\django\contrib\auth\base_user.py",
    line 66, in save
        super().save(*args, **kwargs) TypeError: save() got an unexpected keyword argument 'user'</p>
    
    <p>---------------------------------------------------------------------- Ran 1 test in 0.172s</p>
    
    <p>FAILED (errors=1) Destroying test database for alias 'default'...</p>
  </blockquote>
  
  <p>and no users are being created. What can I do to solve it?</p>