Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django's test client with multiple values for data keys

Tags:

django

Django's test client lets you perform POST requests and specify request data as a dict.

However if I want to send data that mimics <select multiple> or <input type="checkbox"> fields, I need to send multiple values for a single key in the data dict.

How do I do this?

like image 759
bradley.ayers Avatar asked Jul 20 '12 01:07

bradley.ayers


2 Answers

The simplest way is to specify the values as a list or tuple in the dict:

client.post('/foo', data={"key": ["value1", "value2"]})

Alternatively you can use a MultiValueDict as the value.

like image 124
bradley.ayers Avatar answered Oct 08 '22 07:10

bradley.ayers


Just ran into this issue! Unfortunately, your answer did not work for me, In the FormView I was posting to it would only pull out one of the values included, not all of the values

You should also be able to build a querystring manually and post it using content type x-www-form-urlencoded

some_str = 'key=value1&key=value2&test=test&key=value3'
client.post('/foo/', some_str, content_type='application/x-www-form-urlencoded')
like image 44
dm03514 Avatar answered Oct 08 '22 07:10

dm03514