【问题标题】: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&amp;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'].

    【讨论】:

      猜你喜欢
      • 2022-12-02
      • 2022-12-02
      • 2022-12-31
      • 2022-12-01
      • 2022-12-27
      • 2022-12-27
      • 2022-12-02
      • 2022-12-19
      • 2022-12-01
      相关资源
      最近更新 更多