Im using Django 1.3.1.In my django code, i have the following template for the main page, its called main_page.html:
<html>
<head>
<title>My Site</title>
</head>
<body>
<h1>Welcome</h1>
{% if user.username %}
<p>Welcome {{ user.username }}!</p>
{% else %}
<p>Welcome anonymous user!
You need to <a href="/login/">login</a>
{% endif %}
</body>
</html>
I have the following view for this template:
def main_page(request):
template = get_template('main_page.html')
variables = Context({'user': request.user})
output = template.render(variables)
return HttpResponse(output)
This works as expected,i.e. it checks if the user has already logged in or not and greets accordingly. But if i replace the above view with the code below, then i always get the message for anonymous user on the main page, irrespective of whether i have logged in or not.
def main_page(request):
return render_to_response(
'main_page.html',
{'user': request.user}
)
What could be going wrong here ?. Please help.
Thank You
In the template you should use
{% if request.user.is_authenticated %}instead of your{% if user.username %}. That should solve your problem.On the other hand, I don’t know, why you’re trying to explicitly add the
uservariable in the view. Why not using something like: