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.

2

2 Answers 2

7

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

@login_required
def my_view(request):
    user = request.user
    do_something(user)
    ...
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.