How do I get the values of all selected checkboxes in a Django request.POST?

DjangoDjango Forms

Django Problem Overview


Hi I have an array of checkboxes e.g.

<input type="checkbox" name="checks[]" value="1" />
<input type="checkbox" name="checks[]" value="2" />
<input type="checkbox" name="checks[]" value="3" />
<input type="checkbox" name="checks[]" value="4" />

How do I access these in the view.py if more than one is selected?

I have tried

request.POST['checks']

but that only gives me the last value. What I want is all the ones that have been selected in a list e.g. 1,3,4

Thanks

Django Solutions


Solution 1 - Django

Try this:

some_var = request.POST.getlist('checks')

some_var will contain [1,3,4] (those values that were checked)

Solution 2 - Django

This will fix your problem,

some_var = request.POST.getlist('checks[]')

If you write some_var = request.POST.getlist('checks') may not work properly.

Solution 3 - Django

this is will work:

<input type="checkbox" name="checks[]" value="1" />
<input type="checkbox" name="checks[]" value="2" />
<input type="checkbox" name="checks[]" value="3" />
<input type="checkbox" name="checks[]" value="4" />

views.py

some_var = request.POST.getlist('checks[]')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohnView Question on Stackoverflow
Solution 1 - DjangoSilver LightView Answer on Stackoverflow
Solution 2 - DjangokartheekView Answer on Stackoverflow
Solution 3 - DjangoAhmed ElgammudiView Answer on Stackoverflow