2015-06-10 91 views
-1

我是django中的新成員,我正嘗試創建註冊並登錄用戶。我已經完成了註冊頁面,並且有些用戶正在註冊,這些註冊信息存儲在我的數據庫中。當我要登錄時,無法找到已註冊的用戶。你能幫我一下嗎?如何檢查登錄用戶登錄Django?

我view.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)) 
+3

請閱讀[文檔](https://docs.djangoproject.com/en/1.8/topics/auth/default/#how-to-log-a-user-in)。 –

回答

0

authenticate()方法檢查一個usernamepassword

您應該修改這一行:

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

是:

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

然而,這是假設你已經設定了認證,接受電子郵件作爲用戶名。

0

通過與用戶名默認的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

檢查您的用戶數據庫中的第一

+0

我已經停止了你的指示,但現在仍然不起作用。 – Ranajit

+0

用戶保存在您的數據庫中? – GrvTyagi

0

記住使用插入set_password()加密的密碼來創建用戶。例如:

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

Login view

0

你剛纔設置的電子郵件領域唯一的,那麼它應該允許獨特 用戶只否則會引發驗證錯誤,如「用戶與 此電子郵件已經存在。 「