How to receive dictionary in post data python

10,951

You can try getting the list as follows:

request.POST.getlist('ids[]')

Note: You will be better off if you send/receive your data as JSON. You first need to set the Accept and Content-Type headers to application/json while sending the request and then convert the json to python object using json.loads. Example as follows:

Javascript/AJAX

$.ajax(
    type: 'POST',
    url:    'http://example.com/api/users',
    contentType: 'application/json'
    data:   {ids:[1,2,3,4,5],type:'info'},
    complete: function(response) {
        console.log(response);
    }
);

Django

import json

def get_users(request):
    ids = request.POST.get('ids')
    if ids:
        ids = json.loads(ids)

Update:

In case you need to use more complicated data such as an object (dictionary) using json will be your best bet and it will work pretty similar to the above example.

Javascript/AJAX

$.ajax(
    type: 'POST',
    url:    'http://example.com/api/users',
    contentType: 'application/json'
    data:   {ids:{"x":"a", "y":"b", "z":"c"}, type:'info'},
    complete: function(response) {
        console.log(response);
    }
);

Django

import json

def get_users(request):
    ids = request.POST.get('ids')
    if ids:
        ids = json.loads(ids)
Share:
10,951
Rohit Khatri
Author by

Rohit Khatri

I am a highly resourceful, innovative, and competent PHP developer with extensive experience in the layout, design and coding of websites specifically in PHP format. Possessing considerable knowledge of the development of web applications and scripts using PHP programming language and MySQL.

Updated on June 04, 2022

Comments

  • Rohit Khatri
    Rohit Khatri almost 2 years

    I'm trying to send array as a parameter to the api which is using python and django framework.

    Here's my client side code that is being used to access the api:

    $.ajax(
        type: 'POST',
        url:    'http://example.com/api/users',
        data:   {user:{name:'Rohit Khatri', age:20, father_name:'S.K'},type:'info'},
        complete: function(response) {
            console.log(response);
        }
    );
    

    Here's the view where I'm trying to access the request parameters

    def get_users(request):
        print(request.POST.get('ids'))
    

    and when I try to access ids parameter, It gives None. If anyone has faced the same problem, please help me.

  • Rohit Khatri
    Rohit Khatri over 7 years
    I have changed the scenario, actually I want to send dictionary inside a field, not list, can you update your answer for that situation?
  • Rohit Khatri
    Rohit Khatri over 7 years
    Using the first way. request.POST.getlist('ids[]') ?
  • Igor Brejc
    Igor Brejc almost 4 years
    @RohitKhatri you should have updated the whole example, there are no ids in your AJAX post's data.