0

I have the following test

def test_bulk_post(my_faker,factory):
    snippets = [{'code':'print(True)'},{'code':'print(True)'},{'code':'print(True)'}]
    assert factory.post('/snippets/',snippets) == True

I am trying to extend the snippets app in the tutorial to accept multiple code objects in a single post request.

Right now this gives me:

/venv/lib/python3.8/site-packages/django/test/client.py(244)encode_multipart()

*** AttributeError: 'list' object has no attribute 'items'

so its not expecting a list.. But I want to give it one. How do I do that?

4
  • What exactly do you mean by array of objects, are you trying to send JSON ? Commented Feb 18, 2021 at 1:07
  • @iklinac see that array in my snippets variable? Those are what I hope to make into Snippet objects. I would like to post them all at once rather than 1 by 1. I also tried doing json.dumps(snippets) but then I get *** AttributeError: 'str' object has no attribute 'items' Commented Feb 18, 2021 at 1:11
  • This does not look like form encoded data, that is why I am asking if you are trying to POST them as JSON body Commented Feb 18, 2021 at 1:15
  • @iklinac. yes I am trying to post them as a json body. I believe thats what the APIRequestFactory's .post() method will do, though Im basically not sure how to use this .post() method with an array like what I have. Does that clarify the question? Commented Feb 18, 2021 at 1:33

1 Answer 1

1

factory.post by default expects a key, value pairs that goes with multipart/form-data and not list hence error

You should probably set content_type='application/json' to pass data as JSON body

factory.post('/snippets/',snippets, content_type='application/json )
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for this. It looks like you can also specify format='json' rather than the content_type. I was confused especially because its hard to find documentation on the APIRequestFactory, but it seems like the api client methods kinda of work the same way? django-rest-framework.org/api-guide/testing
Yes, it works in similar fashion but without the actual request being made, in a moment I though you were using Django RequestFactory which does not have format parameter and not DRF one APIRequestFactory

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.