在Django中,我有一个运行良好的应用程序,直到尝试了本指南所说的内容:https://scribles.net/deploying-existing-django-app-to-heroku/
现在,当我尝试与用户登录时,它总是返回NonType
应用程序正常打开,我可以找回密码,对其进行修改。...但不登录。
该数据库包含用户,因此尚未删除。
当我在django shell中执行以下语句时,得到以下信息:
user = authenticate(username='email@gmail.com', password='1234')
user.name
AttributeError:'NoneType'对象没有属性'name'
>>>tpye(user)
<class 'NoneType'>
这使我认为身份验证总是向我返回NonType,因为User对象确实具有name属性。
我试图通过运行以下命令来修复它:
pipenv uninstall django-heroku
pipenv clean
pipenv install (all packages again)
pipenv lock
我试图修复它的错误数据库,然后再次创建它并删除在settings.py文件中创建的标头
一个奇怪的事实是,当我尝试在不连接互联网的情况下打开应用程序的数据库时(它是本地的,因此我不需要互联网...而且之前也不需要它)。以下消息: Image
这在我的代码中应该不是问题,因为自上次工作以来我还没有编辑任何东西,它一定与git bash或在遵循本教程时添加的依赖项有关。...< / p>
我的文件:
settings.py
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: keep the secret key used in production secret!
SECRET_KEY = 'key'
AUTH_USER_MODEL = 'home.Usuario'
# 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',
'widget_tweaks',
'home',
]
AUTHENTICATION_BACKENDS = ('home.backends.UserAuthentificacionBackend',)
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 = 'cryptoassistant.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'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 = 'cryptoassistant.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/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'email'
EMAIL_HOST_PASSWORD = 'password'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
用户模型
class Usuario(AbstractUser):
name = models.CharField(max_length=12, help_text="The name must be between 2 and 12 characters")
email = models.EmailField(max_length=60, unique=True, help_text="The email must be between 5 and 30 characters")
password = models.CharField(max_length=78)
change_password_code = models.CharField(blank=True,max_length=15)
activated = models.BooleanField(default=False)
activated_code = models.CharField(default="",max_length=15)
ip = models.CharField(blank=True,max_length=15)
last_login = models.DateField(default=now)
wallets = models.ManyToManyField(Wallet)
coins = models.ManyToManyField(Coin)
avatar = models.CharField(blank=True,default="bitcoin.png",max_length=15)
delete_code = models.CharField(default="",max_length=9,blank=True)
two_factors_auth = models.BooleanField(default=False)
two_factors_auth_code = models.CharField(default="",max_length=12,blank=True)
fingerprint = models.CharField(max_length=64,blank=True)
private_wallets = models.ManyToManyField(PrivateWallet, blank=True)
deleted = models.BooleanField(default=False)
API_key = models.CharField(max_length=30, blank=True)
有什么主意吗?
非常感谢!
答案 0 :(得分:1)
authenticate()
验证一组凭据。它使用默认情况下的用户名和密码,针对每个身份验证后端检查它们,如果凭据对后端有效,则返回一个User对象。看来您确定用户名和密码凭据正确无误。
但是,如果凭据对于任何后端均无效或后端引发PermissionDenied
,则它将返回None
。
所以,我对发生的事情有预感:
您具有用于创建用户的用户模型(Usario
)。但是,在您的自定义用户模型或BaseAbstract用户模型之间未关联用于验证用户身份的用户名。这是您需要做的:
from __future__ import unicode_literals
from django.db import models
from django.core.mail import send_mail
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.base_user import AbstractBaseUser
from django.utils.translation import ugettext_lazy as _
from .managers import UserManager
class User(AbstractBaseUser, PermissionsMixin):
name = models.CharField(max_length=12, help_text="The name must be between 2 and 12 characters")
email = models.EmailField(max_length=60, unique=True, help_text="The email must be between 5 and 30 characters")
password = models.CharField(max_length=78)
change_password_code = models.CharField(blank=True,max_length=15)
activated = models.BooleanField(default=False)
activated_code = models.CharField(default="",max_length=15)
ip = models.CharField(blank=True,max_length=15)
last_login = models.DateField(default=now)
wallets = models.ManyToManyField(Wallet)
coins = models.ManyToManyField(Coin)
avatar = models.CharField(blank=True,default="bitcoin.png",max_length=15)
delete_code = models.CharField(default="",max_length=9,blank=True)
two_factors_auth = models.BooleanField(default=False)
two_factors_auth_code = models.CharField(default="",max_length=12,blank=True)
fingerprint = models.CharField(max_length=64,blank=True)
private_wallets = models.ManyToManyField(PrivateWallet, blank=True)
deleted = models.BooleanField(default=False)
API_key = models.CharField(max_length=30, blank=True)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
# Here you can define any number of methods on your new custom user model that may be useful, for example, sending your user an email:
def email_user(self, subject, message, from_email=None, **kwargs):
'''
Sends an email to this User.
'''
send_mail(subject, message, from_email, [self.email], **kwargs)
然后,在与models.py文件相同的目录中创建一个名为managers.py
的文件,并添加以下内容:
from django.contrib.auth.base_user import BaseUserManager
class UserManager(BaseUserManager):
use_in_migrations = True
def _create_user(self, email, password, **extra_fields):
"""
Creates and saves 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):
extra_fields.setdefault('is_superuser', False)
return self._create_user(email, password, **extra_fields)
def create_superuser(self, email, password, **extra_fields):
extra_fields.setdefault('is_superuser', 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)
就是这样,您的新身份验证方法(一旦创建了新用户)就可以在您的自定义用户模型上使用! :)
免责声明:添加此代码后,您可能需要运行$ python manage.py makemigrations
和$ python manage.py migrate
。