2014-12-05 123 views
0

所以,我想顯示記錄/未記錄的用戶不同的菜單。Django,記住用戶登錄

如果用戶沒有登錄(登錄,註冊)

如果他已經登錄:(主,我的個人資料,註銷)

views.py:

@csrf_protect 
def loginn(request): 
c = {} 
c.update(csrf(request)) 
return render_to_response("login/login.html",c) 


@csrf_protect 
def auth_view(request): 
    username = request.POST.get('username', '') 
    password = request.POST.get('password', '') 
    user = authenticate(username=username, password=password) 
    if user is not None: 
     if user.is_active: 
      login(request, user) 
      return render_to_response('login/loggedin.html',RequestContext(request)) 
    else: 
     return HttpResponseRedirect('/posts/invalid') 

和模板:

{% block Menu %} 
{% if not request.user.is_authenticated %} 
    <li> <a href="/posts/login">Login</a> </li> 
    <li> <a href="/posts/register/">Register</a></li> 
{% endif %} 

{% if request.user.is_authenticated %} 
     <li><a href="/posts">Main</a></li> 
     <li><a href="#">My profile</a></li> 
     <li><a href="/posts/logout">logout</a></li> 
    {% endif %} 
{% endblock %} 

當我登錄頁面我點擊提交,下頁它完美的作品。有登錄用戶的菜單選項。 但是,無論我會做什麼(刷新頁面,轉到主頁等)我會看到沒有登錄用戶的菜單選項。

我讀過用戶認證Django文檔,現在我知道那 在{% if user.is_authenticated %}模板只能與RequestContext,如果我得到它的權利,也沒有辦法做我想做這樣。

我想讓Django記住,無論我在做什麼(刷新頁面,單擊鏈接等),用戶都會一直登錄Django有沒有辦法做到這一點?

那麼如何記住用戶已經登錄並在模板中使用它?

也許有另一種方式來記住用戶登錄並在模板中使用它?會議,烹飪等的東西?

p.s.對不起我的英文不好

+1

嘗試使用user.is_authenticated改爲只request.user.is_authenticated – 2014-12-05 08:50:40

+0

而不是使用'render_to_response'使用'render' – 2014-12-05 08:58:40

+0

@vijayshanker我之前已經試過這,問題保持不變。 – 2014-12-05 08:59:06

回答

2

第一點:爲確保您的上下文處理器能夠正常工作,您必須在所有視圖中使用RequestContext。最簡單的方法是使用render()快捷方式(https://docs.djangoproject.com/en/1.6/topics/http/shortcuts/#render)而不是render_to_response()。第二點:HTTP是一種無狀態協議,因此爲了讓您的應用程序記住請求之間的任何內容,您需要會話支持。從你描述的內容來看,我強烈懷疑你忘記了啓用SessionMiddleware(參見https://docs.djangoproject.com/en/1.6/topics/auth/)。

+0

但是,如果我在所有視圖中使用'RequestContent',我仍然會遇到刷新頁面和直接鏈接到主頁面的問題。 'django.contrib.sessions.middleware.SessionMiddleware'在settings.py – 2014-12-05 09:11:01

+0

使用'RequestContext'不會解決會話問題,它只會確保您可以訪問所有模板中的請求。 Wrt /會話,除了啓用中間件之外,還有一點需要 - 您還需要配置會話後端(https://docs.djangoproject.com/en/1.6/topics/http/sessions/#configuring-the-會話引擎)。首先確保你已經正確配置好了,如果你使用db後端,會創建會話表等。 – 2014-12-05 09:19:20

+0

謝謝,現在我知道什麼是錯的! – 2014-12-05 09:24:45