1

网址.py

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

视图.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>

这里 rest.id = 1

怀疑

当我将“餐厅”键声明为字典时,我无法理解,当我单击“like”按钮时,它不会返回所有键,每次只返回一个键,例如当我单击 food_like 按钮时,它的返回关键 food_like 但是当我再次单击 service_like 按钮而不是返回所有 food_like 和服务就像它刚刚返回服务一样,请帮助。提前致谢

基本上我想要的是创建嵌套会话字典,例如。

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

1 回答 1

1

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
于 2012-08-23T15:33:29.213 回答