这是我的问题,我想验证一个自定义 AbstractBaseUser 。
if request.POST:
username = request.POST['username']
password = request.POST['password']
user = auth.authenticate(username=username, password=password)
print user
if user is not None:
...
我的用户信息是用户名:tom,密码:tom。当我签入 shell 时,我有一个带有这些信息的 SimpleUser,所以它退出了。现在,当我在 django 控制台中打印用户时,它会打印无。但是,当我查看 Django 的信息时,它说
{'username': u'tom', u'csrf_token': <django.utils.functional.__proxy__ object at 0x7fbb681fc650>, 'errors': ['Username/password error'], 'password': u'tom'}
因此,据我所知,用户名和密码是正确的。怎么了 ?
编辑:创建 SimpleUser :
class SimpleUser(AbstractBaseUser):
username = models.TextField(max_length=40, unique=True)
firstname = models.TextField(max_length=40)
lastname = models.TextField(max_length=40)
email = models.EmailField()
society = models.TextField(max_length=255)
objects = UserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['password', 'society', 'email']
编辑 2:在 views.py 中注册视图:
def registerview(request):
firstname = ""
lastname = ""
username = ""
password01 = ""
password02 = ""
email = ""
society = ""
errors = []
hlinks = [("http://localhost:8000/", "Index"),
("http://localhost:8000/login", "Login"),
("http://localhost:8000/register", "Register"), ]
if request.POST:
firstname = request.POST['firstname']
lastname = request.POST['lastname']
username = request.POST['username']
password01 = request.POST['password01']
password02 = request.POST['password02']
email = request.POST['email']
society = request.POST['society']
if (password01 != "" and password01 == password02 and firstname != "" and lastname != "" and username != "" and email != "" and society != ""):
try:
SimpleUser.objects.get(username=username)
except SimpleUser.DoesNotExist:
try:
SimpleUser.objects.get(email=email)
except SimpleUser.DoesNotExist:
u = SimpleUser(firstname=firstname,
lastname=lastname,
username=username,
password=password01,
email=email,
society=society)
u.save()
return HttpResponseRedirect('/login/')
errors.append(
"invalide user/pass")
else:
errors.append("fill all fields")
c = {
'headerlinks': hlinks,
'footerlinks': footerlinks,
'firstname': firstname,
'lastname': lastname,
'username': username,
'email': email,
'society': society,
'errors': errors,
}
c.update(csrf(request))
return jinja_render_to_response('registerview.jhtml', c)
编辑 3:添加我的 backends.py:
from models import SimpleUser
class SimpleUserAuth(object):
def authenticate(self, username=None, password=None):
try:
user = SimpleUser.objects.get(username=username)
if user.check_password(password):
return username
except SimpleUser.DoesNotExist:
return None
def get_user(self, user_id):
try:
user = SimpleUser.objects.get(pk=user_id)
if user.is_active:
return user
return None
except SimpleUser.DoesNotExist:
return None