How to get array of values from checkbox form Django

霸气de小男生 提交于 2021-02-10 09:26:48

问题


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>

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

size_ids = request.data['model_size_ids[]']

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!


回答1:


Use the getlist method for geting the list of selected choices

request.POST.getlist('model_size_ids[]')


来源:https://stackoverflow.com/questions/44628251/how-to-get-array-of-values-from-checkbox-form-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!