13

Django 的测试客户端允许您执行POST请求并将请求数据指定为dict.

但是,如果我想发送模拟<select multiple><input type="checkbox">字段的数据,我需要为 data 中的单个键发送多个值dict

我该怎么做呢?

4

3 回答 3

21

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.

于 2012-07-20T01:04:15.583 回答
4

刚碰到这个问题!不幸的是,您的答案对我不起作用,在FormView我发布的内容中,它只会提取其中一个值,而不是所有值

您还应该能够手动构建查询字符串并使用内容类型发布它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')
于 2014-01-08T16:54:34.157 回答
2
from django.core.urlresolvers import reverse
from django.utils.datastructures import MultiValueDict
from django.utils.http import urlencode

form_data = {'username': 'user name',
             'address':  'street',
             'allowed_hosts': ["host1", "host2"]
             }

response = client.post(reverse('new_user'),
                       urlencode(MultiValueDict(form_data), doseq=True),
                       content_type='application/x-www-form-urlencoded')
于 2016-05-19T09:40:55.430 回答