2011-10-17 14 views
1

我遇到了我的django站點的用戶身份驗證問題。我有一個似乎可以工作的登錄屏幕。當用戶點擊登錄時,我打電話給django.contrib.auth.login,它似乎工作正常。但是在後續頁面上並不知道有用戶登錄。示例{% user.is_authenticated %}爲false。還有一些菜單功能可供登錄用戶使用,如my-accountlogout。除登錄頁面外,這些功能不可用。這真的很奇怪。Django中的用戶上下文

這似乎是一個用戶上下文問題。但我不確定我應該如何傳遞上下文以確保我的登錄穩定。 base.html文件的Does anyone know at could be going on here? Any advice?

--------- ------------部分

<!--- The following doesn't register even though I know I'm authenticated --> 
{% if user.is_authenticated %} 
      <div id="menu"> 
      <ul> 
      <li><a href="/clist">My Customers</a></li> 
      <li><a href="#">Customer Actions</a></li> 
      <li><a href="#">My Account</a></li> 
      </ul> 
      </div> 
{% endif %} 

---------我的看法。 PY -----------------

# Should I be doing something to pass the user context here 
def customer_list(request): 
    customer_list = Customer.objects.all().order_by('lastName')[:5] 
    c = Context({ 
     'customer_list': customer_list, 
     }) 
    t = loader.get_template(template) 
    return HttpResponse(t.render(cxt)) 

回答

3

如果你使用Django 1.3,可以使用render()快捷方式,它會自動包括RequestContext爲您。

from django.shortcuts import render 

def customer_list(request): 
    customer_list = Customer.objects.all().order_by('lastName')[:5] 
    return render(request, "path_to/template.html", 
       {'customer_list': customer_list,}) 

在這種情況下,你可能會進一步走一步,並使用通用ListView

from django.views.generic import ListView 

class CustomerList(Listview): 
    template_name = 'path_to/template.html' 
    queryset = Customer.objects.all().order_by('lastName')[:5] 
+0

偉大的作品!謝謝! – codingJoe

1

正如丹尼爾建議,使用RequestContext的...或更好的,只是使用render_to_response快捷:

from django.template import RequestContext 
from django.shortcuts import render_to_response 

def customer_list(request): 
    customer_list = Customer.objects.all().order_by('lastName')[:5] 
    return render_to_response(
     "path_to/template.html", 
     {'customer_list':customer_list,}, 
     context_instance=RequestContext(request))