In a form I want to use a list that contains all items from a ChoiceField that have not been selected yet. In order to do this I want to iterate through the choices and discard the ones that are selected (i.e. have selected="selected" in their html)
在一个表单中,我想使用一个列表,其中包含尚未选择的ChoiceField中的所有项目。为了做到这一点,我想迭代选择并丢弃所选的(即在他们的html中选择=“选中”)
class MethodForm(ModelForm):
def __init__(self, *args, **kwargs):
super(MethodForm, self).__init__(*args, **kwargs)
#pseudo-code starts here
exclude = []
for val in self.fields['someM2Mfield'].choices:
exclude.append(val.is_selected)
#/pseudocode
rule_choices = get_rule_choices(exclude)
self.fields['rule'] = forms.ChoiceField(rule_choices)
...
The pseudocode bit is where I don't know what methods/properties to use. Can anyone enlighten me?
伪代码位是我不知道使用什么方法/属性的地方。任何人都可以开导我吗?
PS: I am able to iterate through the choices by calling next()
on self.fields[].choices.__iter__
, but how do I determine whether the choice is selected?
PS:我可以通过调用self.fields []。choices .__ iter__上的next()来迭代选择,但是如何确定选择是否被选中?
1 个解决方案
#1
1
The form's self.inital
should give you a dictionary with the initial values for all fields of the form. So self.initial['someM2Mfield']
should return the already selected values. If you need the list of selected choices you might do something like:
表单的self.inital应该为您提供一个字典,其中包含表单所有字段的初始值。所以self.initial ['someM2Mfield']应该返回已经选择的值。如果您需要所选选项列表,您可能会执行以下操作:
selected_values = self.initial['someM2Mfield']
rule_choices = [(value, text) for value, text in
self.fields['someM2Mfield'].choices
if value in selected_values]
#1
1
The form's self.inital
should give you a dictionary with the initial values for all fields of the form. So self.initial['someM2Mfield']
should return the already selected values. If you need the list of selected choices you might do something like:
表单的self.inital应该为您提供一个字典,其中包含表单所有字段的初始值。所以self.initial ['someM2Mfield']应该返回已经选择的值。如果您需要所选选项列表,您可能会执行以下操作:
selected_values = self.initial['someM2Mfield']
rule_choices = [(value, text) for value, text in
self.fields['someM2Mfield'].choices
if value in selected_values]