Django auth.authenticate一直没有返回

时间:2015-03-26 02:28:56

标签: python django authentication

当我尝试对用户进行身份验证以便他们可以登录时,auth.authenticate会一直返回

models.py

class User(AbstractBaseUser):
    fname = models.CharField(max_length=20, blank = False)
    lname = models.CharField(max_length=20, blank = False)
    email = models.EmailField(max_length=50, unique = True, db_index = True, blank = False)
    course_id = models.CharField(max_length=20, default='DEFAULT VALUE')
    role = {}
    USERNAME_FIELD = 'email'
    objects = UserManager()

views.py:

def user_signup_save(request):
    fname = request.POST.get('fname')
    lname = request.POST.get('lname')
    email = request.POST.get('email')
    password = request.POST.get('password')
    user = User(fname = fname, lname = lname, email = email)
    user.set_password('password')

    user.save()
    return HttpResponse(user.password)


def login(request):
    email = request.POST.get('email')
    password = request.POST.get('password')
    user = auth.authenticate(email = email , password = password)
    print user
    if user is not None:
        auth.login(request, user)
        return HttpResponse("valid, logged in")
    else:
        return HttpResponse("invalid, not logged in")
    pass

此外,在用户注册并将它们存储在数据库中后,当我尝试使用check_password(string)比较其密码时,当我使用原始密码和散列密码时,它总是返回false。我正在使用的后端是'django.contrib.auth.backends.ModelBackend'。有什么建议吗?

1 个答案:

答案 0 :(得分:3)

您的问题在这里:

user.set_password('password')

您将密码设置为字符串password,而不是用户键入的密码。因此问题

将其更改为

user.set_password(password) #Note the quotes around the variable password

使用password作为现有用户的密码,您会惊讶地看到authenticate以预期的方式响应;)