2012-05-24 52 views
0

我目前正在研究一個Django項目以更熟悉Django。目前,我正在嘗試製作兩個模板,一個是主頁面,其中包含指向登錄頁面的鏈接,它將登錄用戶,然後返回到模板並顯示其他內容(將通過nginx處理)和另一個模板只能在登錄時才能訪問。出於某種原因,但似乎沒有工作,或者讓我們說登錄不起作用。如何在Django中登錄用戶?

這是views.py文件:

from django.shortcuts import render_to_response, get_object_or_404, HttpResponse 
from django.contrib.auth import * 
from django.contrib.auth.decorators import login_required 

def index(request): 
     return render_to_response('index.html') 

@login_required 
def main(request): 
    return render_to_response('loginrequired.html') 

這是主模板:

{% load static %} 
{% get_static_prefix as STATIC_PREFIX %} 

<html> 
<head> 
<title>Django NGINX Test</title> 
</head> 
<body> 
<h1>Django NGINX Test</h1> 
<img src="{{STATIC_PREFIX}}beach.jpg"/> 
<BR><BR> 
<h2> 
{% if user.is_authenticated %} 
    <a href="test">Log out</a> {{user.username}} 
{% else %} 
    <a href="login">Log in</a> 
{% endif %} 
</h2> 
</body> 
</html> 

這是login_required模板:

{% load static %} 
{% get_static_prefix as STATIC_PREFIX %} 

<html> 
<head> 
<title>Django NGINX Test</title> 
</head> 
<body> 
<h1>Django NGINX Test</h1> 
<img src="{{STATIC_PREFIX}}beach.jpg"/> 
<BR><BR> 
Welcome {{user.username}}. You're now logged in as required.<BR><BR> 
<h2> 
{% if user.is_authenticated %} 
    <a href="test">Log out</a> {{user.username}} 
{% else %} 
    <a href="login">Log in</a> 
{% endif %} 
</h2> 
</body> 
</html> 

最後,但至少我的登錄模板:

<html> 
<head> 
    <title>User Login</title> 
</head> 
<h1>User Login</h1> 
{% if form.errors %} 
    <p>Your username and password didn't match. 
     Please try again.</p> 
{% endif %} 
<form method="post" action="." > 
{% csrf_token %} 
    <p><label for="id_username">Username:</label> 
     {{ form.username }}</p> 
    <p><label for="id_password">Password:</label> 
     {{ form.password }}</p> 
    <input type="hidden" name="next" value="/" /> 
    <input type="submit" value="login" /> 
</form> 
</body> 
</html> 

我將不勝感激任何幫助。我已經研究過Django教程,但我沒有得到它。

+0

它以什麼方式不起作用?當您嘗試訪問需要登錄的頁面時會發生什麼? – murgatroid99

+0

什麼是錯誤? – sumit

+0

那麼,當我嘗試訪問login_required模板時,它只是向我顯示,而不要求登錄。我不確定,如果我已經登錄,但它不顯示我的用戶名或者我必須以某種方式將它傳遞給視圖? – masterlampe

回答

5

你需要確保你包括你的settings.py以下中間件:

  • SessionMiddleware
  • AuthenticationMiddleware

爲了確保命名user上下文變量是提供給您的模板,您需要確保django.contrib.auth.context_processors.auth上下文處理器位於您的settings.py中。

更多信息可在Djano auth topic找到。

+1

借用這個答案:如果你沒有使用上面鏈接中列出的表單和方法,你就會讓事情變得更加困難。 – Tom

+0

由於@Tom提到的原因+1,並補充說您應該使用['render'](http://django.me/render)快捷鍵來確保包含「RequestContext」。 –

1

用戶已登錄,但未傳遞給模板,因此不會顯示用戶詳細信息。確保使用RequestContext呈現模板,或者使用新的render快捷鍵代替render_to_response

相關問題