Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is Django's client.post nesting arg values in lists?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

(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?

>Solution :

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'].

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading