Search code examples
djangoauthenticationdjango-context

User Context in Django


I am having problems with user authentication for my django site. I have a log-in screen that seems to work. When the user clicks log-in, I call the django.contrib.auth.login and it seems to work fine. However on subsequent pages have no knowledge that there is a user logged in. Example {% user.is_authenticated %} is false. There are also some menu functions that I want to be available for logged in users such as my-account and logout. Those functions are not available, except on the log-in page. Which is really strange.

This seems to be a user context problem. But I'm not sure how I am supposed to be passing a context around to ensure that my login is stable. Does anyone know at could be going on here? Any advice?

---------part of 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 %}

---------my 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))

Solution

  • If you're using Django 1.3, you can use the render() shortcut, which automatically includes RequestContext for you.

    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,})
    

    In this case, you could go one step further, and use the generic ListView:

    from django.views.generic import ListView
    
    class CustomerList(Listview):
        template_name = 'path_to/template.html'
        queryset = Customer.objects.all().order_by('lastName')[:5]