1

我的 django 站点的用户身份验证存在问题。我有一个似乎可以工作的登录屏幕。当用户单击登录时,我调用django.contrib.auth.login 它,它似乎工作正常。但是在后续页面上不知道有用户登录。示例 {% user.is_authenticated %}是错误的。还有一些我希望登录用户可以使用的菜单功能,例如my-accountlogout。除登录页面外,这些功能不可用。这真的很奇怪。

这似乎是一个用户上下文问题。但我不确定我应该如何传递上下文以确保我的登录是稳定的。 Does anyone know at could be going on here? Any advice?

---------base.html的一部分------------

<!--- 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 %}

---------我的views.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))
4

3 回答 3

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]
于 2011-10-17T18:04:21.143 回答
2

使用RequestContext

于 2011-10-17T16:39:32.733 回答
1

正如 Daniel 建议的那样,使用 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)) 
于 2011-10-17T17:46:07.820 回答