2012-08-23 77 views
2

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) 

疑問

我得到的問題,同時設置會話鍵使用變量字符串, 我怎麼設置「像」裏面「餐廳」鍵??會話密鑰,請大家幫忙Django的會話,以防止用戶從多個投票

回答

0

首先創建一個空的字典 request.session[restaurant] = dict()

然後做作業 request.session[restaurant][like] = str(like)