JQuery Ajax Post in Django View

I am trying to find a better way to send message data to a Django View function.

What I have in my jquery code looks 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"); } }); 

Data comes in to Django in a QueryDict object:

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

In the view function, I can access the following values:

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

It somehow seems wrong (accessing mail data via getlist and then getting the first item in the list) as a way to transfer post data from jquery to django. Is there a better way to send data?

+6
source share
3 answers

It may be the โ€œright wayโ€ for this, although it is not easier.

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

 JSONdata = request.POST['data'] 

and then decode the JSON data:

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

and you will get all the JSON data in the dict variable. Usage example:

 username = dict['name'] 
+5
source

Why do you need to use getlist at all? Django QueryDict objects use lists for all elements, but simple get - or even regular dictionary access - always gets the first element. So:

 name = request.POST['name'] 

works great.

Also, I don't understand how you create a JS object in the first place. What is the point ""+name ? Why not just {name: name, age: age} ?

+4
source

You can create a form and put code that stores this data in a .save method. This way you will also receive a free check. If you are doing multiple queries for a query. POST and checks in the view, you may have separated the problems incorrectly.

If you want to save this data in a model, use the ModelForm class (you can make a form with only some model fields).

 class PersonForm(forms.Form): name = forms.Charfield(max_length=50) age = forms.IntegerField(min_value=0, max_value=150) def save(self): data = self.cleaned_data # do what you need here # protect the view with require_POST decorator from django.views.decorators.http import require_POST @require_POST def myview(request): form = PersonForm(data=request.POST) form.save() 

Another advantage of the form is that you can display it on the page and using the jquery.form.js plugin send it to ajax without manually clicking any data:

 $('#personform').ajaxForm({ success: function one, error: function two }) 
+3
source

Source: https://habr.com/ru/post/899214/


All Articles