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!

2 Answers 2

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.)!
    ...
Sign up to request clarification or add additional context in comments.

7 Comments

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"?
No that shouldn't be a problem. Could I see your views file?
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}))
<form action ='/checkbox' method='GET'> <input type="checkbox" id="dark" value="dark"> <input type="checkbox" id="white" value="white"> <input type="checkbox" id="nougat" value="nougat"> </form>
I am very sorry for the format, but I am not allowed to post an answer in my own question after 8 hours
|
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.

1 Comment

When I try that, it gives me an error 'Request' object has no attribute 'GET'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.