Django Authentication
In my base.html file I am using
Here, even if the user is logged in, the login button appears.{% if user.is_authenticated %}
<a href="#">{{user.username}}</a>
{% else %} <a href="/acc/login/">log in</a>
Now when I click on the link log in
it shows the username as well as the normal login name, saying the user is logged in.
So what's wrong?
a source to share
It looks like you are not getting any user information in your templates. You need 'django.contrib.auth.middleware.AuthenticationMiddleware'
in customization MIDDLEWARE_CLASSES
, and to get this kindness 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 get you all of this, consider using the django-annoying decorator render_to
instead 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))
a source to share
I'm sure Dominic Roger's answer solves your problem. 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 my_data_dictionary
:
return direct_to_template(request, 'template.html', foo=qux, bar=quux, ...)
a source to share