title: Custom authentication in Django
body: <p>Does anybody know what problem it might be. I'm doing custom authentication in order to use token authentication without passing username but email adres instead, during first login. When I run first makemigrations I constantly get </p>
  
  <blockquote>
    <p>django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'main.User' that has not been installed</p>
  </blockquote>
  
  <p>I'm pretty sure I have app of that name in installed app.</p>
  
  <p><a href="https://thinkster.io/tutorials/django-json-api/authentication" rel="nofollow noreferrer">Tutorial I've mentioned about</a></p>
  
  <p>My folders str:</p>
  
  <pre><code>+---main
  |   +---migrations
  +---squanchy_learn_rest_api
  </code></pre>
  
  <p>models.py:</p>
  
  <pre><code>from datetime import datetime, timedelta
  from django.contrib.auth.models import AbstractUser
  from django.db import models
  from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
  from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
  from django.conf import settings
  
  class UserManager(BaseUserManager):
      """Define a model manager for User model with no username field."""
  
      use_in_migrations = True
  
      def _create_user(self, email, password, **extra_fields):
          """Create and save a User with the given email and password."""
          if not email:
              raise ValueError('The given email must be set')
          email = self.normalize_email(email)
          user = self.model(email=email, **extra_fields)
          user.set_password(password)
          user.save(using=self._db)
          return user
  
      def create_user(self, email, password=None, **extra_fields):
          """Create and save a regular User with the given email and password."""
          extra_fields.setdefault('is_staff', False)
          extra_fields.setdefault('is_superuser', False)
          return self._create_user(email, password, **extra_fields)
  
      def create_superuser(self, email, password, **extra_fields):
          """Create and save a SuperUser with the given email and password."""
          extra_fields.setdefault('is_staff', True)
          extra_fields.setdefault('is_superuser', True)
  
          if extra_fields.get('is_staff') is not True:
              raise ValueError('Superuser must have is_staff=True.')
          if extra_fields.get('is_superuser') is not True:
              raise ValueError('Superuser must have is_superuser=True.')
  
          return self._create_user(email, password, **extra_fields)
  
  
  class User(AbstractUser):
      objects = UserManager()
      username = None
      id = models.IntegerField(primary_key=True, auto_created=True, blank=True)
      name = models.CharField(null=True, blank=True, max_length=50)
      email = models.EmailField(null=True, unique=True)
      password = models.CharField(max_length=50, blank=True,)
      password_2 = models.CharField(max_length=50, blank=True,)
      is_active = models.BooleanField(default=True)
      created_at = models.DateTimeField(auto_now_add=True)
      updated_at = models.DateTimeField(auto_now=True)
  
      # The `USERNAME_FIELD` property tells us which field we will use to log in.
      # In this case we want it to be the email field.
      USERNAME_FIELD = 'email'
      REQUIRED_FIELDS = []
  
      # UserManager class defined above should manage
      # objects of this type.
      # For getting more info about overriding methods visit:
      # https://docs.djangoproject.com/en/2.1/topics/auth/customizing/#substituting-a-custom-user-model
  
      def get_full_name(self):
          return self.email
  
      def get_short_name(self):
          return self.name
  
  </code></pre>
  
  <p>settings.py:</p>
  
  <pre><code>
  import os
  
  # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
  BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  
  
  # Quick-start development settings - unsuitable for production
  # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
  
  # SECURITY WARNING: keep the secret key used in production secret!
  SECRET_KEY = '9y&amp;q=wo&amp;g#ylm@p(kn@1!)=5d%q^%kz*^#9a4ns#tusov&amp;$xr1'
  
  # SECURITY WARNING: don't run with debug turned on in production!
  DEBUG = True
  
  ALLOWED_HOSTS = []
  
  
  # Application definition
  
  INSTALLED_APPS = [
      'django.contrib.admin',
      'django.contrib.auth',
      'django.contrib.contenttypes',
      'django.contrib.sessions',
      'django.contrib.messages',
      'django.contrib.staticfiles',
      'rest_framework',
      'rest_framework.authtoken',
      'djoser',
      'main',
  ]
  
  MIDDLEWARE = [
      'django.middleware.security.SecurityMiddleware',
      'django.contrib.sessions.middleware.SessionMiddleware',
      'django.middleware.common.CommonMiddleware',
      'django.middleware.csrf.CsrfViewMiddleware',
      'django.contrib.auth.middleware.AuthenticationMiddleware',
      'django.contrib.messages.middleware.MessageMiddleware',
      'django.middleware.clickjacking.XFrameOptionsMiddleware',
  ]
  
  ROOT_URLCONF = 'squanchy_learn_rest_api.urls'
  
  TEMPLATES = [
      {
          'BACKEND': 'django.template.backends.django.DjangoTemplates',
          'DIRS': [],
          'APP_DIRS': True,
          'OPTIONS': {
              'context_processors': [
                  'django.template.context_processors.debug',
                  'django.template.context_processors.request',
                  'django.contrib.auth.context_processors.auth',
                  'django.contrib.messages.context_processors.messages',
              ],
          },
      },
  ]
  
  WSGI_APPLICATION = 'squanchy_learn_rest_api.wsgi.application'
  
  # AUTH_USER_MODEL = 'app.User'
  
  REST_FRAMEWORK = {
  
      'DEFAULT_AUTHENTICATION_CLASSES': (
      'rest_framework.authentication.TokenAuthentication',
      'rest_framework.authentication.SessionAuthentication',),
  }
  
  # Database
  # https://docs.djangoproject.com/en/2.2/ref/settings/#databases
  
  DATABASES = {
      'default': {
          'ENGINE': 'django.db.backends.sqlite3',
          'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
      }
  }
  
  
  # Password validation
  # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
  
  AUTH_PASSWORD_VALIDATORS = [
      {
          'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
      },
      {
          'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
      },
      {
          'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
      },
      {
          'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
      },
  ]
  
  AUTH_USER_MODEL = 'main.User'
  
  
  # Internationalization
  # https://docs.djangoproject.com/en/2.2/topics/i18n/
  
  LANGUAGE_CODE = 'en-us'
  
  TIME_ZONE = 'Europe/Warsaw'
  
  USE_I18N = True
  
  USE_L10N = True
  
  USE_TZ = True
  
  
  # Static files (CSS, JavaScript, Images)
  # https://docs.djangoproject.com/en/2.2/howto/static-files/
  
  STATIC_URL = '/static/'
  </code></pre>
  
  <p>Full(almost) folders and files structure:</p>
  
  <pre><code>C:.
  │   manage.py
  │   Pipfile
  │   Pipfile.lock
  │
  ├───.idea
  │   │   .gitignore
  │   │   misc.xml
  │   │   modules.xml
  │   │   squanchy-lean-rest-api-2.iml
  │   │   vcs.xml
  │   │   workspace.xml
  │   │
  │   └───inspectionProfiles
  │           profiles_settings.xml
  │
  ├───main
  │   │   admin.py
  │   │   apps.py
  │   │   models.py
  │   │   serializers.py
  │   │   tests.py
  │   │   views.py
  │   │   __init__.py
  │   │
  │   ├───migrations
  │   │   │   __init__.py
  │   │   │
  │   │   └───__pycache__
  │   │           __init__.cpython-38.pyc
  │   │
  │   └───__pycache__
  │           admin.cpython-38.pyc
  │           models.cpython-38.pyc
  │           serializers.cpython-38.pyc
  │           tests.cpython-38.pyc
  │           views.cpython-38.pyc
  │           __init__.cpython-38.pyc
  │
  └───squanchy_learn_rest_api
      │   settings.py
      │   urls.py
      │   wsgi.py
      │   __init__.py
      │
      └───__pycache__
              settings.cpython-38.pyc
              urls.cpython-38.pyc
              wsgi.cpython-38.pyc
              __init__.cpython-38.pyc
  </code></pre>