I would like to explain some of the complex issues we might come across while sending data using Ajax.
We can access it simply in Django view
# Django Code print request.POST['key1'] # prints value1 if value1 is not array
We need to use getlist in Django to access array items
# Python Code key1 = request.POST.getlist("key1") #Dont forget . It returns the list [1,2,3] key2 = request.POST['key2'] #Simple strings can be accessed normally
Let us assume we are sending some complex data like this.
Since key1 is a JSON object, we need to convert it(not the whole data) to JSON string before sending using ajax.
We need to convert this JSON string to dictionary in Python.
# Django Code key1 = json.loads(request.POST['key1']) # request.POST['key1'] returns a string but json.loads converts it to dictionary key2 = request.POST.getlist("key2") #Returns a list key3 = request.POST['key3'] #Simple string can be accessed directly.
Do you know any better way to do this ? Feel free to mention in comments.
We develop web applications to our customers using python/django/angular.
Contact us at firstname.lastname@example.org