2

if I have the following html:

<form method ='GET' action='/search'>
<input type='checkbox' name='box1' id='box1'> Option 1
<input type='checkbox' name='box2' id='box2'> Option 2
<input type='submit'>
</form>

How could I know whether one of the checkbox was selected (TRUE/FALSE) in python/django? I am writing an app in Django and I would like to show a specific result depending on which checkboxes were selected.

Many thanks in advance!

vcvd
  • 422
  • 2
  • 7
  • 13

2 Answers2

4

If it exists in request.GET, it was checked, if it is not, it was not checked.

see this question: Does <input type="checkbox" /> only post data if it's checked?

Edit: example check:

if 'box1' in request.GET:
    # checked!
    ...
else
    # not checked (or the form was never submitted.)!
    ...
Community
  • 1
  • 1
jproffitt
  • 6,225
  • 30
  • 42
  • Thanks for the answer, but when I use it, it does not remember that I checked it. Could it be possible that I have to change from method="get" to method = "post"? – vcvd Oct 10 '13 at 15:59
  • No that shouldn't be a problem. Could I see your views file? – jproffitt Oct 10 '13 at 16:00
  • `def checkbox(request): filter = "" flavour =["dark", "white", "nougat"] for f in flavour: if f in request.GET: filter += f return HttpResponse(render_to_string('page.html',{'filter':filter}))` – vcvd Oct 10 '13 at 16:18
  • I am very sorry for the format, but I am not allowed to post an answer in my own question after 8 hours – vcvd Oct 10 '13 at 16:20
  • I see you error. You need a `name="dark"`, etc. on your inputs. I think you did `value=` instead of `name=`. – jproffitt Oct 10 '13 at 16:22
  • ouuu that's true! sorry about that! – vcvd Oct 10 '13 at 16:41
4

A couple of ways to accomplish this.

if not request.GET.get('checkboxName', None) == None:
  # Checkbox was selected
  selectedFunction()
else:
  notSelectedFunction()

# Another Way
if 'checkbox' in request.GET:
  # Checkbox was selected
  function()
else:
  notSelectedFunction()

Now if you are trying to get data from a posted form just change it from GET.get to POST.get - I would advise if you are trying to 'remember' what was selected to store it in a session or in a cookie. Sessions will be a lot easier to setup and will work just the same as cookies. However, if this is for a 'remember me' a cookie would be the best choice to remember the data.

Jody Fitzpatrick
  • 357
  • 1
  • 11