Access to Django Session with React

32 Views Asked by At

I'm new to React and I wanna Access my Django sessions with React framework.
In this case I have an array in my session named UserInfo that I can access with request.session['UserInfo'] in Django.
I wanna know how can I get UserInfo data in React side and work with it?
Literally how can we get or pass data from frontend to backend between these two?

1

There are 1 best solutions below

0
willeM_ Van Onsem On BEST ANSWER

You can not access session variables, or at least not directly, you will need an API to retrieve these. session variables are stored at the server-side, and normally used for sensitive data you don't want to expose to the client.

You could thus make a small view that we can use to fetch the data:

def user_info(request):
    return JsonResponse({'data': request.session.get('UserInfo')})

and then work with an AJAX request, to fetch the data.

But be careful! Don't create a view that can retrieve an arbitrary key:

# don't do this!!

def session_info(request, key):
    return JsonResponse({'data': request.session.get(key)})