2017-09-14 36 views
0

我有一個要求,從登錄頁面跳轉到管理頁面,你知道URL地址應該更改爲管理頁面。我如何通過請求,如果我重定向,然後呈現模板

如果我只使用渲染管理頁面,URL地址不會改變,所以在這個post我得到了OptimusCrime的很好的答案。

但是,如果我重定向,然後呈現模板,我無法將請求從登錄頁面傳遞到管理頁面。

在登錄頁面的views.py:

... 
return redirect('/app_admin/index/') 

在管理頁面的views.py:

... 
return render(request, 'app_admin/index.html') # there the request is None. 

我怎樣才能將請求傳遞給管理頁面的views.py?

+0

你應該真的考慮學習HTTP協議是如何工作的...... –

回答

1

你應該看看一些基本的Django教程,例如this one,它描述瞭如何創建一個登錄處理程序。

大意是這樣的:

在用戶提交表單視圖,您評估用戶名和/或密碼。如果提交了正確的信息(用戶名和密碼),則將該信息保存在會話中。將用戶重定向到登錄(受限)區域並檢查會話。如果會話具有正確的信息,則允許用戶查看內容,否則重定向用戶。

簡單的登錄邏輯(舉例):

def login(request): 
    m = Member.objects.get(username=request.POST['username']) 
    if m.password == request.POST['password']: 
     # Username and password is correct, save that the user is logged in in the session variable 
     request.session['logged_in'] = True 
     request.session['username'] = request.POST['password'] 
     # Redirect the user to the admin page 
     return redirect('/app_admin/index/') 
    else: 
     # Username and/or password was incorrect 
     return HttpResponse("Your username and password didn't match.") 

簡單的管理頁面邏輯(舉例):

def admin_index(request): 
    # Make sure that the user is logged in 
    if 'logged_in' in request.session and request.session['logged_in']: 
     # User is logged in, display the admin page 
     return render(
      request, 
      'app_admin/index.html', 
      {'username': request.session['username']} 
     ) # You can now use {{ username }} in your view 
    # User is not logged in and should not be here. Display error message or redirect the user to the login page 
    return HttpResponse("You are not logged in") 

請注意,這是兩個不同的意見(和URL),即您必須在您的urlpatterns中映射。

+0

如果我想在'/ app_admin/index /'中使用密碼,我是否應該在會話中存儲密碼?或者更好地使用'/ login /'中的密碼。 – 244boy

+0

除了登錄用戶之外,不應該使用用戶密碼。但是,您可以在會話變量中保存想要的任何信息。看到我更新的答案,我保存當前的用戶名。 – OptimusCrime

+0

我使用密碼來連接其他應用程序,所以我在/ login /中進行連接,非常感謝。 – 244boy

相關問題