简体   繁体   中英

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': 'test2@getmixim.com',
                'note': note
            },
            {
                'email': 'notauser@getmixim.com',
                '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': 'test2@getmixim.com'}", u"{'note': 'this is a note', 'email': 'notauser@getmixim.com'}"]}>
(Pdb) request.DATA['invites']
u"{'note': 'this is a note', 'email': 'notauser@getmixim.com'}"

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM