当我尝试在视图中使用MultiValueDictKeyError
时,我收到了request.POST['my_variable_from_jquery_post']
。我不知道如何解决这个问题,我已经尝试了很多。我正在使用django 1.6。帮助将非常感激。
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 »</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 :(得分: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 »</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')