何らかの理由でDjangoシェルで新しく作成されたユーザを認証できず、何が問題なのかわかりません。シェル内でDjangoユーザを認証できません
>>> from django.contrib.auth import get_user_model
>>> email = "[email protected]"
>>> password = "testpassword"
>>> user = get_user_model().objects.create_user("TestUser", email, password)
新しいユーザーが正しくデータベースに追加されているようだ:
(venv) xxx:xxx xxx$ python ../manage.py shell
Python 3.6.0 (v3.6.0, ...)
[GCC 4.2.1 (...) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
は、新しいユーザーを作成します。非常に愚かな何か...
スタートDjangoのシェルでなければなりません
>>> get_user_model().objects.all()
<QuerySet [<MyUser: [email protected]>]>
>>> u = get_user_model().objects.first()
>>> u.username
'TestUser'
>>> u.email
'[email protected]'
>>> u.password
'pbkdf2_sha256$36000$Onrvxuy09b6r$sCuz/2/bIbeg5j7cfO934kCIvzVdxqo1s1v6x6nwYLY='
ただし、認証に失敗する:
>>> from django.contrib.auth import authenticate
>>> user = authenticate(email = email, password = password)
>>> user.email
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'email'
>>>
私はカスタムユーザーモデルを持っていますので、get_user_model()
を使用しています。
models.py:
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
class MyUserManager(BaseUserManager):
def create_user(self, username, email, password=None):
"""
Creates and saves a User with the given email and password.
"""
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=self.normalize_email(email).lower(),
)
user.username = username
user.is_active = False
user.set_password(password)
user.save(using=self._db)
return user
...
class MyUser(AbstractBaseUser):
email = models.EmailField(verbose_name='email address', max_length=255, unique=True)
is_active = models.BooleanField(default=False)
username = models.CharField(max_length=50, default="Anonymous")
is_guest = models.BooleanField(default=False)
objects = MyUserManager()
USERNAME_FIELD = 'email'
def get_full_name(self):
# The user is identified by their email address
return self.email
def get_short_name(self):
# The user is identified by their email address
return self.email
def __str__(self): # __unicode__ on Python 2
return self.email
...
任意の助けいただければ幸いです!
以下のいずれかに動作しません:
>>> user = authenticate(username="TestUser", password=password)
>>> user.email
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'email'
>>>
輝かしいスポット、ありがとう!私はこれを知っていますが、完全にそれを逃して無力でした。 – Andras