craphunter
craphunter

Reputation: 830

Get Username from a Cookie

I use the backend solution from django. I just want to get a username from the cookie or the session_key to get to know the user. How I can do 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 coming up. What am I doing wrong?

Am I right then that authenticated means he is logged in?

--> Okay this I got! Firstly, if you have some clarification to a question, update the question, don't post an answer or (even worse) another question, as you have done. Secondly, if the user is logged out, by definition he doesn't have a username.

I mean the advantage of Cookies is to identify a user again. I just want to place his name on the webpage. Even if he is logged out. Or isnt't it possible?

Upvotes: 2

Views: 5681

Answers (3)

Benjamin Wohlwend
Benjamin Wohlwend

Reputation: 31878

You can check if a user is authenticated by calling the, apptly named, is_authenticated method. Your code would then look somewhat like 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')

No need to access the session yourself, Django handles all of that automatically (provided you use both django.contrib.sessions and django.contrib.auth).

/edit: in order to have a user's username, he needs to be authenticated. There's no good way around that.

Upvotes: 4

takinbo
takinbo

Reputation: 125

You need to enable the AuthenticationMiddleware and SessionMiddleware in your MIDDLEWARE_CLASSES setting in your settings.py to access request.user in your views.

http://docs.djangoproject.com/en/1.2/topics/auth/#authentication-in-web-requests

You can then access the username using request.user.username

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 600041

piquadrat has absolutely the right answer, but if for some reason you do need to get the user from the session, you call get_decoded() on the session object:

session_data = request.session.get_decoded()
user_id = session_data['_auth_user_id']

Upvotes: 2

Related Questions