简体   繁体   English

Django WebTest:按值选中/取消选中复选框

[英]Django WebTest: Check/uncheck checkbox by value

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. 我的WebTest响应中有一个带有一组复选框的表单(都在相同的字段名称下),我想根据它们的值取消选中其中的一部分。 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 . 另外,这实际上并没有取消选中我想要的框:当我依次遍历表单中的复选框时,不再有值value-i-want的元素:该值已设置为None And when I submit the form it behaves as if the nothing was done to the form. 当我提交表单时,它的行为就像对表单没有做任何事情一样。

Unfortunately your method for setting the checked status of the input will indeed have the unwanted side-effect of the input element being deleted. 不幸的是,您用于设置输入的checked状态的方法确实会删除输入元素的不良副作用。

As per the docs , to mark a checkbox input as being checked you will want to write: 根据docs ,要将复选框输入标记为已选中,您将要编写:

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

Where 'field-i-want' is the value of the name attribute of the input element. 其中'field-i-want'是输入元素的name属性的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM