Search code examples
djangodjango-sessions

defining django session keys dynamically


urls.py

(r'^(?P<restaurant>\d+)/like/(?P<option>\w+)$','like')

views.py

def like(request,option="food",restaurant = 1):
    if request.is_ajax:
        rest = 'rest'
        #option could be 'food' , 'service' , 'speciality'
        like = '%s_like' % str(option)

        if restaurant in request.session:
            if like not in request.session[restaurant]:
                request.session[restaurant][str(like)] =str(like)
                session = [item for item in request.session[restaurant]]
                return HttpResponse(session)
            else:
                session = [item for item in request.session[restaurant]]
                return HttpResponse(session)
        if restaurant not in request.session:

            request.session[restaurant] = {}

html

<a href="/{{rest.id}}/like/{{key|lower}}">
    <button  data-placement="left" data-original-title="{{val.0}} people like {{key|upper}} at {{rest|title}}" rel="tooltip" class="like pull-right pointer btn btn-info text-left pad0  btn-mini mrg-left5 like-food">
        <i class="icon-thumbs-up"></i>&nbsp;{{val.0}}
    </button></a>

here rest.id = 1

doubt

i am not able to understand when i declared 'restaurant' key as a dictionary then , when i click on the like button its not returning all the keys , every time only one key is returned , for example when i click the food_like button , its returning the key food_like but then again when i click on service_like button instead of returning all food_like and service like its just returning service like , please help. thanks in advance

basically what i want is to create nested session dictionary ,for eg.

request.session[restaurant][food][like]
request.session[restaurant][food][dislike] 
request.session[restaurant][service][like]
request.session[restaurant][service][dislike] 

Solution

  • Suggestion: I wouldn't have your dynamic dictionary values in the root session dict, nest it one level for better manageability. see request.session["restaurants"]

    Solution: check out: https://docs.djangoproject.com/en/dev/topics/http/sessions/#when-sessions-are-saved

    request.session[restaurant][str(like)] = str(like)
    

    Does not modify the session and so it does not trigger a save by default.

    Your options are to tell the session that it has been modified

    request.session.modified = True
    

    OR save the session every request: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-SESSION_SAVE_EVERY_REQUEST

    SESSION_SAVE_EVERY_REQUEST = True