DRF test client unable to post list of JSON

2019-07-13 09:19发布

问题:

I've created a ListCreateAPIView, which looks like this:

 13 class CartItemView(generics.ListCreateAPIView):
 14     serializer_class = CartItemSerializer
 15
 16     def get_serializer(self, *args, **kwargs):
 17         if 'data' in kwargs:
 18             data = kwargs['data']
 19             if isinstance(data, list):
 20                 kwargs['many'] = True
 21
 22         return super(CartItemView, self).get_serializer(*args, **kwargs)
 23

and here's the Serializer:

 47 class CartItemSerializer(serializers.ModelSerializer):
 48     menu_item = serializers.PrimaryKeyRelatedField(queryset = MenuItem.objects.all())
 49     cart = serializers.PrimaryKeyRelatedField(queryset = Cart.objects.all(), required=False)
 50
 51     class Meta:
 52         model = CartItem
 53         depth = 1
 54
 55     def create(self, validated_data):
 56         menu_item = validated_data['menu_item']
 57         cart = validated_data['cart']
 58         cart_item = CartItem.objects.create(menu_item = menu_item, cart = cart, no_of_units = validated_data['no_of_units'])
 59         if cart.cart_state == Cart.EMPTY:
 60             cart.item_added_to_cart()
 61             cart.save()
 62         return cart_item

Now, I'm trying to post a list of JSON objects from test like this:

 1 from rest_framework.test import APITestCase
 .....
 17 class CartItemViewTest(APITestCase):
 18     def test_create_cart_items(self):
 22         data = [{'cart': '4', 'total_qty': '5', 'menu_item': '1'}]
 23         cart_item_url = '/api/v1/cart/items/'
 24         response = self.client.post(cart_item_url, data=data)
 26         print response.data
 29         self.assertEqual(len(resp.data['cart_items']), 1)

But it throws the following error:

======================================================================
ERROR: test_create_cart_items (app.tests.CartItemViewTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/ubuntu/src/app/tests.py", line 24, in test_create_cart_items
    response = self.client.post(cart_item_url, data=data)
  File "/home/ubuntu/Envs/rj-venv/local/lib/python2.7/site-packages/rest_framework/test.py", line 168, in post
    path, data=data, format=format, content_type=content_type, **extra)
  File "/home/ubuntu/Envs/rj-venv/local/lib/python2.7/site-packages/rest_framework/test.py", line 89, in post
    data, content_type = self._encode_data(data, format, content_type)
  File "/home/ubuntu/Envs/rj-venv/local/lib/python2.7/site-packages/rest_framework/test.py", line 64, in _encode_data
    ret = renderer.render(data)
  File "/home/ubuntu/Envs/rj-venv/local/lib/python2.7/site-packages/rest_framework/renderers.py", line 678, in render
    return encode_multipart(self.BOUNDARY, data)
  File "/home/ubuntu/Envs/rj-venv/local/lib/python2.7/site-packages/django/test/client.py", line 168, in encode_multipart
    for (key, value) in data.items():
AttributeError: 'list' object has no attribute 'items'

BTW, when I fire that API from a REST client, it works perfectly fine. Is there something wrong with the way I'm using test client to post list of json?

回答1:

You should specify json as format:

response = self.client.post(cart_item_url, data=data, format='json')


回答2:

Try specifying content_type as application/json.

response = self.client.post(cart_item_url, data=json.dumps(data), content_type='application/json')


回答3:

Try:

response = self.client.post(cart_item_url, data=json.dumps(data)), headers={'Content-Type': 'application/json'})


回答4:

You can try this

response = self.client.post(cart_item_url, json.dumps(data), content_type='application/json')

this is working for me