2017-05-16 19 views
0

所以基本上我的問題是,我用系統內置的dajngo驗證用戶後,用戶切換到用戶「admin」保持前一個用戶進入會話。代碼:django - 身份驗證:用戶在通過後續視圖時變成「admin」用戶

from django.contrib.auth import authenticate 
from django.contrib.auth.decorators import login_required 
def new_login_view(request): 

    if request.method == 'POST': 
     data = dict(request.POST) 
     data.pop('csrfmiddlewaretoken') 

     id_client = data['lg_username'][0] 
     pass_client = data['lg_password'][0] 

     user = authenticate(username=id_client, password=pass_client) 

     if user is not None: 
      # A backend authenticated the credentials 
      ... 
      return render(request, 'initial_page.html', dictionary_with_info) 

當我在initial_page.html並激活一個觀點,那就是:

@login_required 
def home(request): 
    if request.method == 'POST': 
     ... 

時,我呼籲request.user我得到:User: admin,而不是之前的用戶。

有什麼想法爲什麼?

回答

2

您只是對用戶進行身份驗證。您還沒有叫login()實際登錄用戶。

from django.contrib.auth import authenticate, login 

def new_login_view(request): 

    if request.method == 'POST': 
     ... 
     user = authenticate(username=id_client, password=pass_client) 
     if user is not None: 
      login(request, user) 
      # Redirect to a success page. 

參見how to log a user in的文檔獲取更多信息。

請注意,Django自帶authentication views。我建議你使用提供的登錄視圖,而不是自己寫。

+0

你是那麼對! – Asher11

相關問題