运行python manage.py makemigrations的问题

时间:2018-06-27 12:42:41

标签: python django sqlite

我正在关注本教程:https://thinkster.io/tutorials/django-json-api/authentication

一旦我进入python manage.py makemigrations步骤,我就会开始遇到问题。这是我第一次运行命令并且没有现有数据库。我将紧跟本教程,对用户模型进行一些更改,例如删除用户名。这是我下面的相关代码:

/Volumes/Macintosh_HD/Documents/conduitapp/conduit/conduit/apps/authentication/models.py

import jwt

from datetime import datetime, timedelta

from django.conf import settings
from django.contrib.auth.models import (
    AbstractBaseUser, BaseUserManager, PermissionsMixin
)
from django.db import models

class UserManager(BaseUserManager):
    def create_user(self, email, password):
        """
        Create and return a `User` with an email and password.
        """
        if email is None:
            raise TypeError('Users must have an email address.')

        if password is None:
            raise TypeError('Superusers must have a password.')

        user = self.model(email=self.normalize_email(email))
        user.set_password(password)
        user.save()

        return user

    def create_superuser(self, email, password):
        """
        Create and return a `User` with superuser (admin) permissions.
        """
        if email is None:
            raise TypeError('Users must have an email address.')

        if password is None:
            raise TypeError('Superusers must have a password.')

        user = self.create_user(email, password)
        user.is_superuser = True
        user.is_staff = True
        user.save()

        return user

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(db_index=True, unique=True)

    # Allows user to deactivate their account when they no longer want 
    # to continue using our service
    is_active = models.BooleanField(default=True)

    # The `is_staff` flag is expected by Django to determine who can and cannot
    # log into the Django admin site. For most users this flag will always be
    # false.
    is_staff = models.BooleanField(default=False)

    # A timestamp representing when this object was created.
    created_at = models.DateTimeField(auto_now_add=True)

    # A timestamp reprensenting when this object was last updated.
    updated_at = models.DateTimeField(auto_now=True)

    # More fields required by Django when specifying a custom user model.

    # 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 = ['email']

    # Tells Django that the UserManager class defined above should manage
    # objects of this type.
    objects = UserManager()

    def __str__(self):
        return self.email

    @property
    def token(self):
        return self._generate_jwt_token()

    def get_email(self):
        return self.email

    def get_full_name(self):
        """
        This method is required by Django for things like handling emails.
        Typically this would be the user's first and last name. Since we do
        not store the user's real name, we return their email instead.
        We will store first and last name in the future.
        """
        return self.username

    def get_short_name(self):
        """
        This method is required by Django for things like handling emails.
        Typically, this would be the user's first name. Since we do not store
        the user's real name, we return their email instead.
        We will store first and last name in the future.
        """
        return self.username

    def _generate_jwt_token(self):
        """
        Generates a JSON Web Token that stores this user's ID and has an expiry
        date set to 1 day into the future. We may want to consider decreasing time.
        """
        dt = datetime.now() + timedelta(days=1)

        token = jwt.encode({
            'id': self.pk,
            'exp': int(dt.strftime('%s'))
        }, settings.SECRET_KEY, algorithm='HS256')

        return token.decode('utf-8')

/Volumes/Macintosh_HD/Documents/conduitapp/conduit/conduit/settings.py

Django settings for conduit project.

Generated by 'django-admin startproject' using Django 2.0.6.

For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""

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.0/howto/deployment/checklist/

# 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',
]

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 = 'conduit.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 = 'conduit.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.0/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.0/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',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/

STATIC_URL = '/static/'

# Tell Django about the custom `User` model we created. The string
# `authentication.User` tells Django we are referring to the `User` model in
# the `authentication` module. This module is registered above in a setting
# called `INSTALLED_APPS`.
AUTH_USER_MODEL = 'authentication.User'

引用如下:

Traceback (most recent call last):
      File "/Volumes/Macintosh_HD/Documents/conduitapp/conduit/venv/lib/python3.6/site-packages/django/apps/registry.py", line 147, in get_app_config
        return self.app_configs[app_label]
    KeyError: 'authentication'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Volumes/Macintosh_HD/Documents/conduitapp/conduit/venv/lib/python3.6/site-packages/django/contrib/auth/__init__.py", line 194, in get_user_model
    return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False)
  File "/Volumes/Macintosh_HD/Documents/conduitapp/conduit/venv/lib/python3.6/site-packages/django/apps/registry.py", line 197, in get_model
    app_config = self.get_app_config(app_label)
  File "/Volumes/Macintosh_HD/Documents/conduitapp/conduit/venv/lib/python3.6/site-packages/django/apps/registry.py", line 154, in get_app_config
    raise LookupError(message)
LookupError: No installed app with label 'authentication'.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "/Volumes/Macintosh_HD/Documents/conduitapp/conduit/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
    utility.execute()
  File "/Volumes/Macintosh_HD/Documents/conduitapp/conduit/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute
    django.setup()
  File "/Volumes/Macintosh_HD/Documents/conduitapp/conduit/venv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/Volumes/Macintosh_HD/Documents/conduitapp/conduit/venv/lib/python3.6/site-packages/django/apps/registry.py", line 120, in populate
    app_config.ready()
  File "/Volumes/Macintosh_HD/Documents/conduitapp/conduit/venv/lib/python3.6/site-packages/django/contrib/admin/apps.py", line 23, in ready
    self.module.autodiscover()
  File "/Volumes/Macintosh_HD/Documents/conduitapp/conduit/venv/lib/python3.6/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover
    autodiscover_modules('admin', register_to=site)
  File "/Volumes/Macintosh_HD/Documents/conduitapp/conduit/venv/lib/python3.6/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules
    import_module('%s.%s' % (app_config.name, module_to_search))
  File "/Volumes/Macintosh_HD/Documents/conduitapp/conduit/venv/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/Volumes/Macintosh_HD/Documents/conduitapp/conduit/venv/lib/python3.6/site-packages/django/contrib/auth/admin.py", line 6, in <module>
    from django.contrib.auth.forms import (
  File "/Volumes/Macintosh_HD/Documents/conduitapp/conduit/venv/lib/python3.6/site-packages/django/contrib/auth/forms.py", line 20, in <module>
    UserModel = get_user_model()
  File "/Volumes/Macintosh_HD/Documents/conduitapp/conduit/venv/lib/python3.6/site-packages/django/contrib/auth/__init__.py", line 199, in get_user_model
    "AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'authentication.User' that has not been installed

0 个答案:

没有答案
相关问题