这是我的问题,我想在。中验证自定义的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
答案 0 :(得分:3)
这不起作用,因为在创建新用户时,您提供密码。所以它作为纯文本存储在数据库中,而不是散列值。当你调用authenticate函数时,它将检查散列值。
在您的注册表中,您应使用objects.create_user
或使用set_password(password)