Authenticate method has stopped working

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Authenticate method has stopped working



I have an application in Django that worked perfectly until I tried what this guide says: https://scribles.net/deploying-existing-django-app-to-heroku/



Now when I try to log in with a user, it always returns a NonType



The application opens normally, I can recover the password, modify it.... but do not log in.



The DB contains the user, so it has not been deleted.



When I execute the following statement in the django shell I get the following:


user = authenticate(username='email@gmail.com', password='1234')
user.name



AttributeError: 'NoneType' object has no attribute 'name'


>>>tpye(user)
<class 'NoneType'>



Which makes me think that authenticate is always returning a NonType to me, because the User object does have the name property.



I've tried to fix it by running the following commands:


pipenv uninstall django-heroku
pipenv clean
pipenv install (all packages again)
pipenv lock



I've tried to fix it errase DB and created it again and removing the header I created in the settings.py file



As a curious fact, when I try to open the application's database without being connected to the internet, (it's local, so I shouldn't need the internet... and I didn't need it before) I get the following message:
Image



It should not be a problem in my code because I haven't edited anything since the last time it worked, it has to be something related to git bash or dependencies that have been added while following the tutorial....



My files:



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



user model


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)



Any idea?



Thanks so much!





Hi XBoss - is it possible to remove my access from the repository you added me to. :)
– user10215593
Aug 15 at 17:44





Sure! thanks so much!
– XBoss
Aug 15 at 17:45





No worries at all - you can find me on twitter @michealjroberts if you need any more help or pointers.
– user10215593
Aug 15 at 17:59




1 Answer
1



authenticate() verifies a set of credentials. It takes username and password for the default case, checks them against each authentication backend, and returns a User object if the credentials are valid for a backend. It looks like you are sure that the username and password credentials are correct.


authenticate()



However, if the credentials aren’t valid for any backend or if a backend raises PermissionDenied, it returns None.


PermissionDenied


None



So, my hunch as to what is going on:



You have a user model (Usario) that you have used to create a User. But the username needed to authenticate your user is not being associated between your custom User model or your BaseAbstract user model. Here's what you need to do:


Usario


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)



Then, create a file named managers.py in the same directory as your models.py file, and add the following:


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)



That should be it, your new authenticate method (once you have created a new User) should work on your custom user model! :)



Disclaimer: you may need to run $ python manage.py makemigrations and $ python manage.py migrate after adding this code.


$ python manage.py makemigrations


$ python manage.py migrate





Comments are not for extended discussion; this conversation has been moved to chat.
– Samuel Liew
Aug 12 at 23:16






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard