django会话以防止用户进行多次投票

时间:2012-08-23 00:13:59

标签: python django django-sessions

views.py

def like(request,option="food",restaurant = 1):
    if request.is_ajax:
        rest = 'rest'
        like = '%s-like' % str(option)

        if restaurant in request.session:

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


        r = Restaurant.objects.get(pk=restaurant)
        if option == "food":
            r.food_likes +=1
            r.save()
            return HttpResponse(str(r.food_likes))
        elif option=="service":
            r.service_likes +=1
            r.save()
            return HttpResponse(str(r.service_likes))
        elif option == "ambience":
            r.ambience_likes +=1
            r.save()
            return HttpResponse(str(r.ambience_likes))
    else:
        return redirect(request.META.get('HTTP_REFERER'))

错误

'unicode' object does not support item assignment

线

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

疑问

我在使用变量字符串设置会话密钥时出现问题, 我该怎么设置会话密钥'喜欢'里面的'餐厅'键?,请帮忙

1 个答案:

答案 0 :(得分:0)

首先创建一个空字典 request.session[restaurant] = dict()

然后完成作业 request.session[restaurant][like] = str(like)