Search code examples
djangosessionrequestresponse

How can Django get session data in next request?


def home(request):
    # logged in
    if request.user.is_authenticated:
        request.session['username'] = str(request.user)
        request.session.set_expiry(0)

    # anonymous
    else:
        # how could Django get session data here ?
        cur = request.session.get('username', None)
        if cur:
            pass
        else:
            anon = random.choice(settings.SESSION_NAMES)
            request.session['username'] = anon
            request.session.set_expiry(42)

    res = render(request, 'ex/home.html', {'username': request.session['username']})
    return res

I'm trying to understand about session. In anonymous case above, I set session data 'username' to request that is already obtained. And in next request (after refreshing), I can get session data.

But I don't understand how could it work. It's a new request, and I set 'username' in prev request, not response.

How could I get 'username' from next request object despite not setting it to previous response object?


Solution

  • How could I get 'username' from next request object despite not setting it to previous response object?

    The session data is not stored by the client, but by the server. Data that is stored at the client side are the cookies.

    Django sets a cookie in the browser that by default is named sessionid (you can change this by altering the SESSION_COOKIE_NAME setting [Django-doc], and this thus contains an identifier to the session data stored for this session.

    The browser will thus each time make a request with the sessionid, and if you access request.session, then it will look what it stored in the database.

    You can alter how the server stores the cookies, and what serializer is used. For more information, see the How to use sessions section of the documentation.