Reputation: 9087
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.
Upvotes: 31
Views: 50192
Reputation: 8699
You can use this code
from django.contrib.sessions.models import Session
from importlib import import_module
from django.contrib.auth.middleware import get_user
from django.http import HttpRequest
engine = import_module(settings.SESSION_ENGINE)
SessionStore = engine.SessionStore
session = SessionStore(sessionid)
request = HttpRequest()
request.session = session
user = get_user(request)
Upvotes: 0
Reputation: 31572
This:
def view(request):
if request.user.is_authenticated:
user = request.user
print(user)
# do something with user
Upvotes: 8
Reputation: 6792
In case hwjp solution doesn't work for you ("Data is corrupted"), here is another solution:
import base64
import hashlib
import hmac
import json
def session_utoken(msg, secret_key, class_name='SessionStore'):
key_salt = "django.contrib.sessions" + class_name
sha1 = hashlib.sha1((key_salt + secret_key).encode('utf-8')).digest()
utoken = hmac.new(sha1, msg=msg, digestmod=hashlib.sha1).hexdigest()
return utoken
def decode(session_data, secret_key, class_name='SessionStore'):
encoded_data = base64.b64decode(session_data)
utoken, pickled = encoded_data.split(b':', 1)
expected_utoken = session_utoken(pickled, secret_key, class_name)
if utoken.decode() != expected_utoken:
raise BaseException('Session data corrupted "%s" != "%s"',
utoken.decode(),
expected_utoken)
return json.loads(pickled.decode('utf-8'))
s = Session.objects.get(session_key=session_key)
decode(s.session_data, 'YOUR_SECRET_KEY'))
credit to: http://joelinoff.com/blog/?p=920
Upvotes: 0
Reputation: 18117
An even easier way to do this is to install django-extensions and run the management command print_user_for_session.
And this is how they do it:
Upvotes: 2
Reputation: 16091
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
Upvotes: 82
Reputation: 411142
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.
Upvotes: 20