Reputation: 405
I am trying to change my request.data dict to remove some additional field. It is working completely fine in views. But when I run test cases for the same, I get this error:
AttributeError: This QueryDict instance is immutable
Here is my viewset:
def create(self, request, *args, **kwargs):
context = {'view': self, 'request': request}
addresses = request.data.pop("addresses", None)
serializer = self.get_serializer(data=request.data, context=context)
serializer.is_valid(raise_exception=True)
response = super(WarehouseViewSet, self).create(request, *args, **kwargs)
if addresses is None:
pass
else:
serializer = self.get_serializer(data=request.data, context=context)
serializer.is_valid(raise_exception=True)
addresses = serializer.update_warehouse_address(request, addresses, response.data["id"])
response.data["addresses"] = addresses
return Response(data=response.data, status=status.HTTP_201_CREATED)
and here is my test case for the same view:
def test_create_warehouse_authenticated(self):
response = client.post(
reverse('warehouse_list_create'),
data={
'name': self.test_warehouse['test_warehouse']['name'],
'branch': self.test_warehouse['test_warehouse']['branch'],
},
**{'HTTP_AUTHORIZATION': 'Bearer {}'.format(
self.test_users['test_user']['access_token']
)},
)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
How to fix this error?
Upvotes: 6
Views: 5578
Reputation: 8674
Try setting format='json'
when calling client.post
, rather than relying on the default. You don't mention which test client you are using, but you should be using the APIClient
client = APIClient()
client.login(...)
client.post(..., format='json')
Newer Django has a immutable QueryDict, so this error will always happen if you are getting your data from querystring or a multipart form body. The test client uses multipart
by default, which results in this issue.
Last Resort: If you need to post multipart, and also modify the query dict (very rare, think posting image + form fields) you can manually set the _mutable
flag on the QueryDict to allow changing it. This is
setattr(request.data, '_mutable', True)
Upvotes: 14