使用身份验证不存在用户匹配查询

时间:2015-09-09 09:19:52

标签: python django authentication django-authentication

我使用以下代码创建了一个用户:

views.py (注册视图工作正常但登录视图不正常)

def register(request):  
    if request.method == 'POST':
    form = UserProfileForm(request.POST) 

    if form.is_valid():
        user = form.save()

        username = ... 
        u = User.objects.create_user(username, user.email, user.password)
        u.save()
        ... 

    else:
        return HttpResponse('Nombre o contrasena incorrectos.')
else:
    form = UserProfileForm()

...


def log_in(request):   
if request.method == 'POST':
    form = UserLoginForm(request.POST)
    if form.is_valid():
        email = form.cleaned_data['email']
        password = form.cleaned_data['password']
        try:
            u = User.objects.get(email=email, password=password)
        except User.DoesNotExist:
            return HttpResponse('Email o contrasena incorrectos.')
        ...
else:
    form = UserLoginForm()
...

注册视图创建我的自定义用户没有任何问题,但是当我想用它登录我的应用程序时,登录视图会抛出User.DoesNotExist异常。那是为什么?

1 个答案:

答案 0 :(得分:1)

问题在于:

u = User.objects.get(email=email, password=password)

没有任何意义,你无法比较password字段值,因为它没有以原始数据存储在数据库中。

要检查用户是否提供了正确的密码,您应该使用authenticate内置功能:

u = authenticate(username=username, password=password)

你可以在这里看到实例: http://code.runnable.com/UpBfbcg4PNU0AAHG/how-to-check-if-the-user-is-authenticated-in-django-for-python-authentication-and-httprequest

..或官方Django文档(login函数示例): https://docs.djangoproject.com/en/1.8/topics/auth/default/#django.contrib.auth.login