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?
CodePudding user response:
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 the last record, so 'qux'
. You can also use request.POST.getlist('foo')
it will return all values for that key in a list, so ['bar', 'qux']
.