views:

91

answers:

2

In my base.html file, I am using
{% if user.is_authenticated %}
<a href="#">{{user.username}}</a>
{% else %} <a href="/acc/login/">log in</a>

Here, even if the user is logged in, the log in button shows up.

Now when I click on the log in link, it shows the username and also the normal login view, saying user is logged in.

So, what's wrong?

+4  A: 

Sounds like you're not getting any user information in your templates. You need 'django.contrib.auth.middleware.AuthenticationMiddleware' in your MIDDLEWARE_CLASSES setting, and to get that goodness in context for your templates, you need to do:

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

def my_view(request):
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))

To save you doing this everywhere, consider using django-annoying's render_to decorator instead of render_to_response.

@render_to('template.html')
def foo(request):
    bar = Bar.object.all()
    return {'bar': bar}

# equals to
def foo(request):
    bar = Bar.object.all()
    return render_to_response('template.html',
                              {'bar': bar},
                              context_instance=RequestContext(request))
Dominic Rodger
Thanks, Dominic R. One more thing, so, I need to include `context_instance` in all of my views, if I need to do this always (like show "log in" information in the header)? Isn't there a better way to do this if I always want to do this thing. I hope I am clear.
zubinmehta
@webvulture - take a look at django-annoying (see my edit). I know opinions vary as to whether the `render_to` decorator is evil, but I tend to find it useful. Don't use it if your view is *ever going to do anything* other than render to that template.
Dominic Rodger
A: 

I am sure that the answer of Dominic Rodger solves your issue. Just wanted to add that I personally prefer to import direct_to_template instead of render_to_response:

from django.views.generic.simple import direct_to_template
...
return direct_to_template(request, 'my_template.html', my_data_dictionary)

but I guess it's just a matter of taste. In my case you could also use named parameters instead of my_data_dictionary:

return direct_to_template(request, 'template.html', foo=qux, bar=quux, ...)
mawimawi