joerick
joerick

Reputation: 16448

Django Rest Framework .DATA attribute returning first item of array only

I've got an API endpoint where clients POST a JSON object (to invite a few users at once to a project).

My test looks like this:

def test_new_style(self):
    note = 'this is a note'
    payload = {
        'invites': [
            {
                'email': '[email protected]',
                'note': note
            },
            {
                'email': '[email protected]',
                'note': note
            }
        ]
    }

    # self.u1_client is a rest_framework.test.APIClient object
    response = self.u1_client.post('/api/projects/1/invite', payload)

And I have an APIView that looks like:

class InviteMember(APIView):
    permission_classes = (IsAuthenticated,)

    def post(self, request, project_pk):
        import pdb; pdb.set_trace()

I land in a shell, and do the following:

(Pdb) request
<rest_framework.request.Request object at 0x106bb4910>
(Pdb) request.DATA
<QueryDict: {u'invites': [u"{'note': 'this is a note', 'email': '[email protected]'}", u"{'note': 'this is a note', 'email': '[email protected]'}"]}>
(Pdb) request.DATA['invites']
u"{'note': 'this is a note', 'email': '[email protected]'}"

Weird, right? How can I get at the array of invite dictionaries? Why isn't the DATA attribute just giving me the object?


Django: v1.7.4
Django Rest Framework: v2.4.4

Upvotes: 2

Views: 844

Answers (1)

joerick
joerick

Reputation: 16448

I've found the solution! The problem is that my request was being sent as query string.

Changing my test to...

response = self.u1_client.post('/api/projects/1/invite', payload, format='json')

...fixes the problem.

Actually the DRF APIClient was encoding the individual dicts as JSON and then embedding them in the query string.

Upvotes: 5

Related Questions