justin
justin

Reputation: 1699

Django ajax passing variable to the views

I'm new with Django + Ajax. My Problem is I can't get the value from my ajax POST request. I'm using the jquery post.

My task is to sort the draggable list item. The drag and drop is not the problem. Getting the values from POST request is the problem. It returns MultiValueDictKeyError

"Key 'ages' not found in <QueryDict: {u'action': [u'updateRecords'], u'ages[]': [u'80', u'81', u'79', u'82', u'83', u'84', u'85', u'86']}>"

here is my ajax:

$(function() { 
    var url = ""; /* won't place it*/
    $("ul#ages").sortable({ opacity: 0.6, cursor: 'move', update: function() {
            var order = $(this).sortable("serialize") + '&action=updateRecords';
            $.post(url, order, function(theResponse){
                alert('success');
            });
        }
    });
});

here is the views:

if request.is_ajax():
        if request.POST['action'] == "updateRecords":
            update_record_array = request.POST['ages']

            order_counter = 1;

            for record_id in update_record_array:
                Age.objects.filter(id=record_id).update(order_id=order_counter)
                order_counter += 1

Can anyone help me out?

Thanks!

Upvotes: 0

Views: 1918

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599630

The error message shows what is wrong - you're looking up a key ages, but you're sending something called ages[] with some extra square brackets.

If you've put those brackets in the field name, you don't need them - that's a PHP-ism. (It might not be your fault: jQuery has been known to do add them itself.) In any case, you'll want to use request.POST.getlist(fieldname) to get the list of multiple values associated with that key.

Upvotes: 1

Related Questions