I have an AJAX request call (with JQuery) to my django view. It sends to view this kind of data:
{"cityId": 1, "products_with_priority": [{"id": 1, "priority": 1}, {"id": 2, "priority": 2}, {"id": 3, "priority": 3}, {"id": 4, "priority": 4}, {"id": 5, "priority": 5}]}
In my django view, I'm trying to get this list like this:
def my_view(request):
city_id = request.POST.get('city_id')
products_priorities = request.POST.getlist("products_with_priority")
Where city_id returns 1 and products_with_priority returns empty array.
How it is possible to receive array of dictionaries from request?
Ensure your dataType is json, and stringify your array:
dataType: 'json',
data: {'cityId': 1, 'products_with_priority': JSON.stringify([{"id": 1, "priority": 1}, {"id": 2, "priority": 2}, {"id": 3, "priority": 3}, {"id": 4, "priority": 4}, {"id": 5, "priority": 5}])}
Then use the (standard Python library) json's loads() method in your Django view:
products_priorities = json.loads(request.POST.get('products_with_priority'))
Convert the data to json string.
And receive it like
data = json.loads(request.POST)
send your data in a json string to django view and then
Try
def my_view(request):
data = OrderedDict()
data = json.loads(request.POST)
city_id = data['city_id']