Hi I've got a problem with the Django Template system. When I want to check in the template if a user is logged in with:
{% if user.is_authenticated %}
# success
{% else %}
<p>Welcome, new user. Please log in.</p>
{% endif %}
I dont get to the success part. When I use in a view:
if not request.user.is_authenticated():
return render_to_response('index.html', {'inhalt': 'Not loggged in'})
else:
return render_to_response('index.html', {'inhalt': 'Succesfully loged in'})
it shows me correctly the else part. Hope somebody can help me. Thanks Phil
from django.contrib.auth import authenticate, login def my_view(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) # Redirect to a success page. ... else: # Return an 'invalid ...
The correct way to create a user in Django is to use the create_user function. This will handle the hashing of the password, etc..
There is an example of handling the context in part 4 of the Django tutorial. However, in short...
The best way to do this is with Django's auth context proccessor. Make sure you still have it in your settings. You then need to use RequestContext
This will essentially change your code to this.
from django.template import RequestContext
# ...
return render_to_response('index.html', {
'inhalt': 'Succesfully loged in'
}, RequestContext(request))
Remember to add 'django.core.context_processors.request' to your TEMPLATE_CONTEXT_PROCESSORS in your settings.py
Example:
# Context processors
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
'django.core.context_processors.static',
'django.core.context_processors.request',
'django.contrib.messages.context_processors.messages',
)
And add RequestContext(request):
# import
from django.template import RequestContext
# render
if not request.user.is_authenticated():
return render_to_response('index.html', {'inhalt': 'Not loggged in'})
else:
return render_to_response('index.html', {'inhalt': 'Succesfully logged in'}, RequestContext(request))
In your python you retrieve the user object that is logged in. I.e define a function get_current_user.
so your response would look something like:
class Index(webapp.RequestHandler):
def get(self):
user= get_current_user()
templates.render(self, 'mypage.html', user=user)
Then on your django template you can simply go like:
{% if user %}
<p>Hallo user {{user.name}}</p>
{% else %}
<p>Welcome, new user. Please log in.</p>
{% endif %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With