Search code examples
pythondjangodjango-viewsdjango-sessions

accessing dict values from request.session in views


I'm trying to obtain a session variable within a view but I'm not having much luck. The error I'm receiving is:

list indices must be integers, not str

I have the following session variable/dict being set:

u'bookingContents' :    
    {
    u'bookingID': 40, 
    u'bookingOptionContents': {
        u'activityID': 1, 
        u'activityName': u'Echo Park legging races', 
        u'activityShortDescription': u'YOLO umami occupy, Echo Park leggings meh Kickstarter cardigan. ', 
        u'activityThumbnail': u'/media/activity/1/thumb_test.jpg', 
        u'optionCost': 20, 
        u'optionDayOfWeek': u'Tuesday', 
        u'optionEndTime': u'12:00', 
        u'optionStartDate': u'19/01/2015', 
        u'optionStartTime': u'06:00', 
        u'quantity': 9}, 
    u'bookingOptionID': 1}

I'm trying to access the bookingID and the bookingOptionsContents.quantity values by their label (preferably).

My views code is as follows (for the first bookingID value):

if int(request.session.get('bookingContents.bookingID', False)) == somevalue:

i've also tried:

if int(request.session.get('[bookingContents']['bookingID'], False)) == somevalue:

but i can't seem to get at the values.

Things work within a template, where I can successfully retrieve the values via:

{{request.session.bookingContents.bookingOptionContents.quantity}}
{{request.session.bookingContents.bookingID}}

How do I get the value for bookingID and quantity in a view?


Solution

  • You cannot use a dot notation in the view. I'd follow EAFP style here:

    try:
        value = int(request.session['bookingContents']['bookingID'])
    except (KeyError, ValueError) as e:
        value = None