Session variables not persisiting

Hey I’m new using django, I’m trying to store some information about the user in the session. I’m trying to store the values ‘user’, ‘role’ in the session but when accessing it the values aren’t stored I think I might be missing something can’t figure it out though. Im using

SESSION_ENGINE = ‘django.contrib.sessions.backends.db’

as the session engine. Any ideas?

  @api_view(['POST'])
def check_user_exists(request):
    user = request.data.get('user')
    password = request.data.get('password')

    if not user or not password:
        return Response({"error": "Username and cedula are required."}, status=status.HTTP_400_BAD_REQUEST)

    try:
        userResponse = Usuarios.objects.get(usuario=user) 

        if check_password(password, userResponse.clave):
            request.session['user'] = userResponse.usuario
            request.session['role'] = userResponse.rol_id
            print("Current session:", request.session.items())
            return Response({'exists': True, 'message': f'User {user} authenticated.', 'rol': userResponse.rol_id}, status=status.HTTP_200_OK)
        else:
            return Response({'exists': False, 'message': 'Password incorrect.'}, status=status.HTTP_400_BAD_REQUEST)

    except:
        return Response({'exists': False, 'message': 'User not found.'}, status=status.HTTP_404_NOT_FOUND)

@api_view(['GET'])
def get_user_role(request):
    role = request.session.get('role')
    
    print("Current session:", request.session.items())
    if role:
        return Response({'status':'success', 'message': 'Role acquired', 'role': role})
    else:
        return Response({'status':'error', 'message':'User not logged in'})

Welcome @Chris4Fun !

I think we’re going to need more details about what exactly isn’t working as expected here.

If you’re getting some kind of error, please post the complete error message and traceback.

If something just isn’t giving you the expected results, please identify exactly and completely what it is that isn’t happening that you’re expecting to have happen. (Or, what is happening that you’re not expecting to see.)

I’m using the django rest API framework, I’m trying to store the values ‘user’, ‘role’ in the session but when making the request to the view down below the values aren’t stored

How are you calling both APIs?

Django sessions by default require the use of cookies with a specific session ID. One way to check if you have it set up correctly is to check if the session key is the same across views:

request.session.session_key

If the session keys are different between the views, it means that Django did not recognize the request as coming from the same user’s session since the corresponding cookies were to sent back. Some HTTP clients that you are using on the frontend may not send cookies by default.