2014-01-18 79 views
0

當我嘗試在視圖中使用request.POST['my_variable_from_jquery_post']時,我得到MultiValueDictKeyError。我不知道如何解決這個問題,我嘗試了很多。我使用的是django 1.6。幫助將超級讚賞。無法將.post變量發送到django視圖

HTML

<script> 
$(function(){ 
    $('.add').click(function(){ 
     var id = $(this).attr('id'); 
     $.post("{% url 'myapp.views.add_bet' %}", {off_id: id,}); 
    }); 
}); 
</script> 

<form action="{% url 'myapp.views.add_bet' %}" method="post"> 
    {% csrf_token %} 
    <button class="btn btn-default add" id="{{offer.id}}" >Add &raquo;</button> 
</form> 

查看

def add_bet(request): 
    off_id=request.POST['off_id'] #doesn't work, throws MultiValueDictKeyError 
    offer=Offer.objects.get(pk=1) #the rest works, if I set pk=1, the bet saves 
    b=Bet(offer=offer, user=request.user, submitted=False) 
    b.save() 
    return redirect('myapp.views.index') 
+0

你確保你得到正確的Ajax調用?還有'{{offer.id}}'正確呈現?嘗試將'preventDefault()'放入你的'click'回調中。 – mariodev

+0

你可以從'add_bet'視圖發佈'request.POST'的輸出嗎.. – Amyth

回答

1

這會爲你工作..

<script type="text/javascript"> 
    var frm = $('#FORM-ID'); 
    frm.submit(function() { 
     $.ajax({ 
      type: frm.attr('method'), 
      url: frm.attr('action'), 
      data: frm.serialize(), 
      success: function (data) { 
       $("#SOME-DIV").html(data); 
      }, 
      error: function(data) { 
       $("#MESSAGE-DIV").html("Something went wrong!"); 
      } 
     }); 
     return false; 
    }); 
</script> 

<form action="{% url 'myapp.views.add_bet' %}" method="post" id="#FORM-ID"> 
{% csrf_token %} 
<input type="hideden" name="off_id" value="{{offer.id}}"> 
<button class="btn btn-default add" type="submit" >Add &raquo;</button> 
</form> 


def add_bet(request): 
    off_id=request.POST.get('off_id',None) 
    b=Bet(offer=offer, user=request.user, submitted=False) 
    b.save() 
    return redirect('myapp.views.index') 
+0

喲感謝一羣人 - 添加一個隱藏的輸入,然後更改爲.submit事件與數據:{'off_id':id}工程。我猜serialize()也能工作,但我不太理解它,所以要明確說明 – amchugh89