繁体   English   中英

如何在 Django 中检查登录用户的登录情况?

[英]How can check logged user for signin in django?

我是 Django 新手,我正在尝试为用户创建注册和登录。 我已经完成了注册页面,一些用户正在注册存储在我的数据库中。 当我要登录时,它找不到那些已经注册的用户。 你能帮我解决这个问题吗?

我的观点.py

def login_user(request):
    state = "Please log in below..."
    if request.POST:
        email = request.POST.get('email')
        password = request.POST.get('password')        
        user = authenticate(email=email, password=password)
        if user is not None:
            if  request.user.is_authenticated:
                login(request, user)
                state = "You're successfully logged in!"
            else:
                state = "Your account is not active, please contact the site admin."
        else:
            state = 'email: '+str(email)+' and password: '+str(password)+' is not found'

    return render_to_response('signup_test.html',{'state':state, 'email': email},context_instance=RequestContext(request))

authenticate()方法检查usernamepassword

您应该修改这一行:

user = authenticate(email=email, password=password)

成为:

user = authenticate(username=email, password=password)

但是,这是假设您已设置身份验证以接受电子邮件作为用户名。

默认情况下,django 支持使用用户名登录,所以尝试一些类似的事情

user = authenticate(username=username, password=password)
if user is not None:
    if user.is_active:
        login(request, user)
        # Redirect to a success page.
    else:
        # Return a 'disabled account' error message
        ...
else:

按照这个: https : //docs.djangoproject.com/en/1.8/topics/auth/default/#authenticating-users

首先在您的数据库中检查您的用户

请记住使用插入加密密码的set_password()来创建用户。 例子:

if form.is_valid():
    user = form.save(commit = False)
    user.set_password(form.cleaned_data['password'])
    user.save()

登录视图

您只需将电子邮件字段设置为唯一,那么它应该只允许唯一用户,否则会引发验证错误,例如“使用此电子邮件的用户已存在”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM