1

I'd like to develop an app for multiple clients that displays analytics data specific to their account. So far I've set up my views file using the @login_required decorator for restricted pages. Now I need to identify that user to obtain their data.

A bit of research suggests that I could use:

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

session_key = request.session.session_key()

session = Session.objects.get(session_key=session_key)
uid = session.get_decoded().get('_auth_user_id')

Which obviously returns the user_id, which I can use as a field in the analytics database to identify which user the data belongs to.

Is this the best way to go about doing this, or can anyone suggest a better/more elegant alternative?

Note: I haven't tested the solution I've proposed, it just seems workable in my head.

Mike
  • 1,814
  • 4
  • 22
  • 36
  • Here's a walkthrough of adding user authentication so the page displays the username. : http://mdukehall.wordpress.com/2011/12/15/django-python-adventure-part-4/ – Duke Hall Dec 19 '11 at 16:25
  • Also if you need something more complex/ roles? http://stackoverflow.com/questions/1546670/django-role-based-views – Duke Hall Dec 19 '11 at 16:25

2 Answers2

7

You can access the logged in user on the request object.

@login_required
def my_view(request):
    user = request.user
    do_something(user)
    ...
Alasdair
  • 298,606
  • 55
  • 578
  • 516
1

when you are in a view, you can access the currently logged in user (object) by

def myview(request):
    request.user

    # or, if you want,
    request.user.id
second
  • 28,029
  • 7
  • 75
  • 76