Pregunta

I am getting a MultiValueDictKeyError when I try to use request.POST['my_variable_from_jquery_post'] in a view. I have no idea how to get around this, I've tried a lot. I'm using django 1.6. Help would be super appreciated.

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>

View

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')
¿Fue útil?

Solución

This will work for you..

<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')
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top