Sometimes request.session.session_key is None
<p>I hit a problem when get session_key from <code>request.session</code>.</p>

<p>I am using Django1.8 and Python2.7.10 to set up a RESTful service.</p>

<p>Here is snippet of my login view:</p>

<pre><code>user = authenticate(username=userName, password=passWord)
if user is not None:
    # the password verified for the user
    if user.is_active:
        # app_logger.debug("User is valid, active and authenticated")
        if hasattr(user, 'parent') :
            login(request, user)
            request.session['ut'] = 4 
            # user type 1 means admin, 2 for teacher, 3 for student, 4 for parents
            request.session['uid'] = user.id
            description = request.POST.get('description','')

            request.session['realname'] = user.parent.realname
            request.session['pid'] = user.parent.id
            devicemanage.update_user_device(devicetoken, user.id, ostype, description) 
            children = parentmanage.get_children_info(user.parent.id)
            session_id = request.session.session_key
            user.parent.login_status = True
            user.parent.save()
            return JsonResponse({'retcode': 0,'notify_setting':{'receive_notify':user.parent.receive_notify,'notify_with_sound':user.parent.notify_with_sound,'notify_sound':user.parent.notify_sound,'notify_shake':user.parent.notify_shake},'pid':user.parent.id,'children':children,'name':user.parent.realname,'sessionid':session_id,'avatar':user.parent.avatar,'coins':user.parent.coins})
</code></pre>

<p>Now when this function is called, I see sometimes <code>session_id</code> is <code>None</code> within the response.</p>

<p>So, after debugging (I set breakpoint at the <code>return JsonResponse(...)</code> line), I see that when I hit the breakpoint the <code>request.session._session_key</code> is <code>None</code>, but <code>request.session.session_key</code> is <code>u'j4lhxe8lvk7j4v5cmkfzytyn5235chf1'</code> and <code>session_id</code> is also <code>None</code>. </p>

<p>Does anyone know how can this happen? Why isn't the value of <code>session_key</code> set when assigning it to <code>session_id</code> before returning the response?</p>

<p>According to John's suggestion.</p>

<p>I fixed the problem by this snippet:</p>

<pre><code>if not request.session.session_key:
    request.session.save()
session_id = request.session.session_key
</code></pre>

python django session django-sessions