2011-10-17 13 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))