2014-03-31 64 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('')