Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get logged in user's uid from session in Django?

Tags:

django

I have implemented a registration/login/authentication system using this Django guide.

But, how would I access a user's information from my views so I can send the user's information to a template file?

I want to be able to access a user's ID so I can submit a form with the user's ID attached to the form.

like image 434
egidra Avatar asked Sep 02 '25 14:09

egidra


2 Answers

In case anyone wants to actually extract a user ID from an actual Session object (for whatever reason - I did!), here's how:

from django.contrib.sessions.models import Session
from django.contrib.auth.models import User

session_key = '8cae76c505f15432b48c8292a7dd0e54'

session = Session.objects.get(session_key=session_key)
session_data = session.get_decoded()
print session_data
uid = session_data.get('_auth_user_id')
user = User.objects.get(id=uid)

Credit should go to Scott Barnham

like image 158
hwjp Avatar answered Sep 05 '25 06:09

hwjp


There is a django.contrib.auth.models.User object attached to the request; you can access it in a view via request.user. You must have the auth middleware installed, though.

like image 28
mipadi Avatar answered Sep 05 '25 05:09

mipadi