[Django]-How to set User in request.user in Django using MongoDB

4👍

You can’t set an attribute on session object the way you’re trying to do.

But you can set a key in the session object (since it’s just like a dictionary), like this:

# you can't set a user object directly
# because it's not JSON serializable
# but you can set its `id`
request.session['user_id'] = user.id

Later, you can get the user like this:

user_id = request.session.get('user_id', None)
if user_id:
    user = User.objects.get(id=user_id)
...

To log the user out, all you have to do is delete the key from the session and call flush():

def logout(...):
    try:
        del request.session['user_id']
        request.session.flush()
    except KeyError:
        pass
   ...
👤xyres

3👍

You have to first obtain the user through authenticate and then call login with the returned user

Ref: https://docs.djangoproject.com/en/2.0/topics/auth/default/#django.contrib.auth.login

Example from django’s documentation:

from django.contrib.auth import authenticate, login

def my_view(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(request, username=username, password=password)
    if user is not None:
        login(request, user)
        # Redirect to a success page.
        ...
    else:
        # Return an 'invalid login' error message.
        ...

Leave a comment