【问题标题】:Why is Django's client.post nesting arg values in lists?Why is Django\'s client.post nesting arg values in lists?
【发布时间】:2022-12-19 08:24:51
【问题描述】:
I'm unit testing my api with Django like this:
result = self.client.post( reverse(path), { "arg1":"value" })
Inside the view, I breakpoint.
@api_view(["POST"])
def post_arg(request):
breakpoint()
But when I print the POST data, the values have been added to lists.
(Pdb) request.POST
{ 'arg1': ['value'] }
This example only has one arg, but if I add more they are each added to a list. I don't think this happens when my frontend posts data, so why does it here? And is there a way to not have the values added to a list?
【问题讨论】:
标签:
python
django
testing
【解决方案1】:
I don't think this happens when my frontend posts data.
The same key can be associated multiple times to a value, for example when you use a checkbox with:
<input type="checkbox" name="foo" value="bar">
<input type="checkbox" name="foo" value="qux">
If you check both checkboxes, it will add foo=bar&foo=qux to the request body, so the same key (foo) is associated to both bar and qux.
If you use request.POST['foo'] it will return the value of thelastrecord, so 'qux'. You can also use request.POST.getlist('foo') it will returnallvalues for that key in a list, so ['bar', 'qux'].