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?
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With