2

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.

1

1 Answer 1

8

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)
Sign up to request clarification or add additional context in comments.

3 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.