簡體   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