61

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

3 Answers 3

90

Try this:

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

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

0
40

This will fix your problem,

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

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

2
  • 1
    This is the way you need to do it for Django 1.8+ (I am not sure on the earlier versions or what version the OP was using at the time). Jul 8, 2016 at 7:02
  • 1
    Did you mean getlist('checks', [])? If so, at least in version 1.10, the brackets are not required. getlist will return an empty list by default, for missing keys.
    – John C
    Oct 24, 2016 at 13:59
1

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[]')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.