Django自定义用户模型导致AttributeError:Manager不可用; 'auth.User'已被替换为'authentication.User'

时间:2016-08-24 10:53:18

标签: django

在我的django应用程序中,名为<Grid.Resources> <CollectionViewSource Source="{Binding DOAProperty}" x:Key="possibilities"/> </Grid.Resources> <DataGrid HorizontalAlignment="Left" Height="243" VerticalAlignment="Top" Width="977" AutoGenerateColumns="False" ItemsSource="{Binding iecv}" IsSynchronizedWithCurrentItem="True" > <DataGrid.Columns> <DataGridTextColumn Header="DivID" Binding="{Binding DivisionID}"></DataGridTextColumn> <DataGridTextColumn Header="Name" Binding="{Binding DivisionName}"></DataGridTextColumn> <DataGridTextColumn Header="AuthLevels" Binding="{Binding AuthLevels}"></DataGridTextColumn> <DataGridComboBoxColumn Header="SeletedAuthLevel" ItemsSource="{Binding Source={StaticResource possibilities} }" SelectedItemBinding="{Binding SelectedAuthID, Mode=TwoWay}" SelectedValuePath="AuthLevels" DisplayMemberPath="AuthLevels" /> </DataGrid.Columns> </DataGrid> ,我创建了一个自定义用户模型,主要是在django documentation之后。

在我之前的一个项目中,它曾经有过工作,但现在我说:

authentication

我经常遇到错误:

user = User.objects.get(username=username)

我用python2和python3,django版本1.9和1.10进行了测试

可能出现什么问题?

我的代码:

AttributeError: Manager isn't available; 'auth.User' has been swapped for 'authentication.User'.

models.py

from django.db import models from django.contrib.auth.models import AbstractBaseUser, \ BaseUserManager, PermissionsMixin from django.utils import timezone from django.utils.translation import ugettext_lazy as _ import uuid import base64 class UserManager(BaseUserManager): def create_user(self, username, email, name, password=None): user = self.model( username=username, email=email, name=name, last_login=timezone.now() ) # last_login is defined in AbstractBaseUser user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, password): user = self.create_user( username=username, email=None, name=username, password=password ) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user def generate_registration_code(): return "asd" class User(AbstractBaseUser, PermissionsMixin): # This model should be created in the firest migration: # https://docs.djangoproject.com/en/1.9/topics/auth/customizing/#substituting-a-custom-user-model # We use username, not email as primary user id, because OAuth # implementation via python-social-auth requires this field to # be present. username = models.CharField( verbose_name=_('username'), max_length=255, unique=True ) email = models.EmailField(null=True, blank=True) # name is a human-readable name used to refer to user e.g. "Martin Taylor" # longest full name registered in guinness book is 744 letters-long name = models.CharField( verbose_name=_('name'), max_length=1023, null=True, blank=True ) # We don't need password and last_login fields, because they are # already defined in AbstractBaseUser. # is_active is a variable in AbstractBaseUser set to True, but we # want a separate field for it. is_active = models.BooleanField( _('active'), default=True, help_text=_('Is this user account activated?') ) is_staff = models.BooleanField( _('staff status'), default=False, help_text=_('Is this user allowed to the admin page') ) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) code = models.CharField( null=True, blank=True, default=generate_registration_code, max_length=255, help_text=_(''' Code to be sent via e-mail upon registration or password recovery. ''') ) new_password = models.CharField( null=True, blank=True, default="", max_length=255, help_text=_(''' If user is attempting to change password, this field stores new password until user enters confirmation code. ''') ) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = [] class Meta: verbose_name = _('user') verbose_name_plural = _('users') def __str__(self): return self.username def get_short_name(self): return self.username def get_full_name(self): return self.username

settings.py

更新: 回溯:

"""
Django settings for simple_resserver_jwt project.

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

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

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

import os
import datetime

# 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/1.10/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'co0)lyiwbgi4wz#80gp&y++bga-+iqd8hxq5boiw3d$g(#!yl*'

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

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


# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

AUTH_USER_MODEL = 'authentication.User'


AUTHENTICATION_BACKENDS = ['authentication.backends.AuthBackend', ]


REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',

   )
}

from  rest_framework_jwt.authentication  import JSONWebTokenAuthentication


with open('private') as f:
    PRIVATE_KEY =  f.readlines()

with open('public') as f:
    PUBLIC_KEY =  f.readlines()

JWT_AUTH = {
    'JWT_ENCODE_HANDLER':
    'authentication.utils.jwt_encode_handler',
    'JWT_DECODE_HANDLER':
    'authentication.utils.jwt_decode_handler',

    # 'JWT_RESPONSE_PAYLOAD_HANDLER':
    # 'authentication.utils.jwt_decode_handler',

    'JWT_SECRET_KEY': PRIVATE_KEY,
    'JWT_ALGORITHM': 'RS256',
    'JWT_VERIFY': True,
    'JWT_VERIFY_EXPIRATION': True,
    'JWT_LEEWAY': 0,
    'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=300),
    'JWT_AUDIENCE': None,
    'JWT_ISSUER': None,
    'JWT_ALLOW_REFRESH': False,
    'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7),
    'JWT_AUTH_HEADER_PREFIX': 'Bearer',
}


# Password validation
# https://docs.djangoproject.com/en/1.10/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/1.10/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/1.10/howto/static-files/

STATIC_URL = '/static/'

0 个答案:

没有答案