Ramesh
Ramesh

Reputation: 2337

Get user object using userid in django

Hello i am new to django,

i am creating an authentication system using django.

Once a user is logged in i am storing the value in a session.

 user = authenticate(username=username, password=password)
request.session['mid'] = user.id

and when i refresh i can receive the session id

uid = request.session['mid']

But i am not sure how to get the userdatas from the user id. can any one tell me how can get the user object using the user id.

Upvotes: 4

Views: 25056

Answers (2)

Leonardo.Z
Leonardo.Z

Reputation: 9801

Of course, you can store the user id in request.session, and query the id with django ORM manually.

But after installing the SessionMiddleware and AuthenticationMiddleware middlewares, on a higher level, Django can hook this authentication framework into its system of request objects. I believe most django projects will use the code below to get authenticated user from web requests.

if request.user.is_authenticated():
         user = request.user

Upvotes: 1

Rohan
Rohan

Reputation: 53386

Use simple .get() query.

try:
    uid = request.session['mid']
    userobj = User.objects.get(id=uid)
except User.DoesNotExist:
   #handle case when user with that id does not exist

...

Upvotes: 9

Related Questions