I personally use the after sales solution from django. Among the finest to obtain a username in the cookie or even the session_answer to become familiar with the consumer. The Way I can perform it?
from django.contrib.auth.models import User from django.contrib.sessions.models import Session def start(request, template_name="registration/my_account.html"): user_id = request.session.get('session_key') if user_id: name = request.user.username return render_to_response(template_name, locals()) else: return render_to_response('account/noauth.html')
Only else is approaching. What shall we be held doing wrong?
Shall We Be Held right then that authenticated means he's drenched in?
--> Okay i got! First of all, for those who have some clarification to some question, update the question, don't publish a solution or (a whole lot worse) another question, as you've done. Next, when the user is drenched out, obviously he does not possess a username.
I am talking about the benefit of Snacks would be to identify a person again. Among the finest to put his title around the web page. Even when he's drenched out. Or isnt't it possible?
You should check if your user is authenticated by calling the, apptly named,
is_authenticated method. Your code would take a look somewhat such as this:
def start(request, template_name="registration/my_account.html"): if request.user.is_authenticated(): name = request.user.username return render_to_response(template_name, locals()) else: return render_to_response('account/noauth.html')
You don't need to access the session yourself, Django handles all that instantly (provided you utilize both
/edit: to be able to possess a user's username, he must be authenticated. There is no great way around that.
piquadrat has absolutely the best answer, but when for whatever reason you need to obtain the user in the session, you call
get_decoded() around the session object:
session_data = request.session.get_decoded() user_id = session_data['_auth_user_id']
You have to let the AuthenticationMiddleware and SessionMiddleware inside your MIDDLEWARE_CLASSES establishing your configurations.py to gain access to request.user inside your sights.
After that you can access the username using request.user.username