3

I want to send this request to a django view:

$http({
        method: "post",
        url: "/enterprises/vouchers/_send",
        data: {
            group_id: group_id,
            group_student_ids: [1, 2, 3, 4]
        }
    }).success(function (response) {
        console.log("emails are sent. please check");
    }).error(function () {
        console.log("failed")
    });

In the view I assign them like this:

group_student_ids = request.POST['group_student_ids']
group_id = request.POST['group_id']

"group_id" is assigned as expected but django is throwing MultiValueDictKeyError for the aray object(group_student_ids)

How do I send an array via a post request?

2 Answers 2

1

This should work:

First, change your data to:

data: {
    'group_id': group_id,
    'group_student_ids[]': [1, 2, 3, 4]
}

and in your view:

group_student_ids = request.POST.getlist('group_student_ids[]')

Edit:

Just did some tests in my app; if I print request.POST, I'll get

<QueryDict: {'group_student_ids[]': ['1', '2', '3', '4']}>

And type(group_student_ids) would give <class 'list'>

Sign up to request clarification or add additional context in comments.

4 Comments

I got this when I printed request.POST: <QueryDict: {u'group_student_ids[][2]': [u'3'], u'group_student_ids[][0]': [u'1'], u'group_id': [u'2'], u'group_student_ids[][1]': [u'2'], u'group_student_ids[][3]': [u'4']}>
@Rodrigue - Fixed typos; should be able to work now (I used square brackets when calling getlist())
I don't know why, but it is not working for me. Anyways, I solved this by converting the array into string and splitting it back to the list in the django view. Thank you for your answer)
@Rodrigue: You're welcome; still not sure why it wouldn't work; perhaps have something to do with the view. Also, I did the test in my app using jQuery's $.ajax() instead of AngularJS
0

Try this:

group_student_ids = request.POST.getlist('group_student_ids[]')

7 Comments

got an empty list [] :(
@Rodrigue print request.POST in the view, what you get?
I got this: <QueryDict: {u'group_student_ids[0]': [u'1'], u'group_student_ids[3]': [u'4'], u'group_student_ids[2]': [u'3'], u'group_id': [u'2'], u'group_student_ids[1]': [u'2']}>. So, it turns out that I am getting them but seperately. I don't know why
@Rodrigue change group_student_ids: [1, 2, 3, 4] in ajax call to "group_student_ids[]": [1, 2, 3, 4]
same thing: <QueryDict: {u'group_student_ids[][2]': [u'3'], u'group_student_ids[][0]': [u'1'], u'group_id': [u'2'], u'group_student_ids[][1]': [u'2'], u'group_student_ids[][3]': [u'4']}>
|

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.