How to get array of values from checkbox form Django

igo*_*nko 2 python django django-rest-framework

I have HTML form like this:

    <p>Models Sizes IDs:</p>
    <input type="checkbox" name="model_size_ids[]" value="1">XS</input>
    <input type="checkbox" name="model_size_ids[]" value="2">S</input>
    <input type="checkbox" name="model_size_ids[]" value="3">M</input>
    <input type="checkbox" name="model_size_ids[]" value="4">L</input>
    <button>Submit</button>
Run Code Online (Sandbox Code Playgroud)

I'm trying to receive an array of checked values on server side in my View:

size_ids = request.data['model_size_ids[]']
Run Code Online (Sandbox Code Playgroud)

But, I can extract only one and the last value. So if I check 2-3 values in checkbox form, I receive only last value in my view. I also tried to name input field without bra?kets and the result was the same. Can anybody tell me, how can I solve that? Thanks!

Aks*_*pte 7

使用 getlist 方法获取所选选项的列表

request.POST.getlist('model_size_ids[]')
Run Code Online (Sandbox Code Playgroud)

  • 另请注意,您不需要 Django 名称中的方括号(“[]”)来正确地将其视为列表(此方括号实际上是 PHP hack,而不是 HTTP 规范的一部分) (6认同)