smurf smurf - 1 year ago 84
Python Question

Validating checkboxes from form in Django

Relatively new to Python..

I would like to know how to check if a check box has been selected.
I am reading the form values into a python script and am unsure how to go about validating.

Using the Web Framework Django. The form is being posted back to a script.
I am loading up a dictionary with many different variables. These variables need to then be passed to a shell script, the command to the shell script requires these check box values to be returned in the form of 0 or 1 in order to create a zip file.

I understand this code is not python but it is my understanding of what i am trying to achieve:

if variable.checked == 'yes'
return 1
return 0

Answer Source

The documentation for Django is really quite good. Check out the description of the HttpRequest class for more information on how this part works. The short answer is that you can do something like this:

def myview(request):
    # do stuff
    option_checked = 'myvariable.checkboxoption' in request.REQUEST
    # do more stuff and return the response

That being said, Django also has a comprehensive form widget/validation/extraction subsystem. I'd recommend going through the full tutorial (particularly part 4, which covers forms) and checking out the mailing list to answer any more specific questions about how to use these libraries.