Django WebTest: Check/uncheck checkbox by value

449 Views Asked by At

I've got a form with a set of checkboxes (all under the same field name) in my WebTest response, and I'd like to uncheck some of them according to their value. I've tried this:

my_form = response.forms['form-i-want']
for i in range(len(my_form.fields.get('field-i-want'))):
    if my_form.fields.get('field-i-want')[i].value == "value-to-uncheck":
        my_form.fields.get('field-i-want')[i].checked = False

Obviously this is very hacky looking code and there must be a better way. Also, this doesn't actually uncheck the box I want: when I then iterate through the checkboxes in the form there is no longer an element with the value value-i-want: the value has been set to None. And when I submit the form it behaves as if the nothing was done to the form.

1

There are 1 best solutions below

0
On

Unfortunately your method for setting the checked status of the input will indeed have the unwanted side-effect of the input element being deleted.

As per the docs, to mark a checkbox input as being checked you will want to write:

my_form['field-i-want'] = True

Where 'field-i-want' is the value of the name attribute of the input element.