2014-03-31 66 views
0

我正在使用Django 1.6。並且我遇到錯誤Django異常類型:MultiValueDictKeyError

**Exception Type**: MultiValueDictKeyError 
**Exception Value**:"'chat_room_id'" 

在代碼的上述部分。任何人都可以幫我解決這個問題嗎?

@login_required 
def join(request): 
    ''' 
    Expects the following POST parameters: 
    chat_room_id 
    message 
    ''' 
    p = request.POST 
    r = Room.objects.get(id=int(p['chat_room_id'])) 
    r.join(request.user) 
    return HttpResponse('') 
+0

'p ['chat_room_id']'的價值是什麼?請打印'p'並顯示輸出。 –

+0

我在嘗試打印p時仍然收到相同的錯誤。我是Django的新手,所以我無法糾正它。 – user3480922

+0

檢查我的答案。如果仍然不起作用,請打印request.POST並更新您的問題。 –

回答

0

好像chat_room_idprequest.POSTMultiValueDict。它有一個.get()方法來獲取值。將它與默認值一起使用,以便如果該鍵沒有值,則可以使用默認值。例如。

@login_required 
def join(request): 
    ''' 
    Expects the following POST parameters: 
    chat_room_id 
    message 
    ''' 
    p = request.POST 
    room_id = p.get('chat_room_id', False) 
    # ------------------------------^ Returns False if `chat_room_id` is not in `p` 
    if room_id: 
     r = Room.objects.get(id=int(room_id)) 
     r.join(request.user) 
    else: 
     # throw error 
    return HttpResponse('')