Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Ajax Post to Django View

I'm trying to figure out the best way to send post data to a Django View function.

What I have currently in my jquery code is something like this:

var name = 'Joe';
var age = 20;

$.ajax({
    url:"/do_something/",
    type: "POST",
    data: {name: name, age: age},
    success:function(response){},
    complete:function(){},
    error:function (xhr, textStatus, thrownError){
        alert("error doing something");
    }
});

The data arrives in Django in a QueryDict object:

<QueryDict: {u'name': [u'Joe'], u'age': [u'20']}>

In the view function, I can access the values like this:

def do_something(request):
    if request.POST:
        name = request.POST.getlist('name')[0]
        age = request.POST.getlist('age')[0]

This feels wrong somehow (accessing the post data through a getlist and then getting the first element in the list) as a way to pass post data from jquery to django. Is there a better way to send data?

like image 910
Steve Walsh Avatar asked Oct 13 '11 10:10

Steve Walsh


1 Answers

This might be the "right way" to do this, though it is not any lighter.

You can read the JSON data from HttpRequest object's POST list using [] notation, for example:

JSONdata = request.POST['data']

and then decode the JSON data:

dict = simplejson.JSONDecoder().decode( JSONdata ) 

and you end up having all your JSON data in the dict variable. Example usage:

username = dict['name']
like image 67
supertopi Avatar answered Sep 28 '22 16:09

supertopi