更新:看起来我必须创建自定义小部件(Grouping CheckboxSelectMultiple Options in Django)。我完成后会包含最终代码。
我已经设置了一个类似于另一个SO question的django形式的选择字段。
但是,我想将它设为CheckboxSelectMultiple
窗口小部件,但是在Meta类中这样做会为整个组创建一个复选框。这是我需要在__init__
中做些什么,如果是这样的话?
class FooIterator(models.ModelChoiceIterator):
def __init__(self, *args, **kwargs):
super(models.ModelChoiceIterator, self).__init__(*args, **kwargs)
def __iter__(self):
for thing in MyModel.objects.all():
yield (thing.name, [(x.id, x.name) for x in MyModel2.objects.filter(name=thing.name)])
class MyForm(ModelForm):
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['myField'].choices = FooIterator()
for x in self.fields:
self.fields[x].widget.attrs['class'] = 'input-block-level'
答案 0 :(得分:1)
我假设您正在使用modelForm。
您可以修改 init
中的字段以下是:
class SomethingForm(forms.modelForm):
def __init__(self, *args, **kwargs):
super(SomethingForm, self).__init__(*args, **kwargs)
self.field['myfieldname'] = forms.CharField(
widget=forms.HiddenInput)
答案 1 :(得分:0)
答案 2 :(得分:0)
class MyForm(ModelForm):
field_name = forms.MultipleChoiceField(required=False,
widget=CheckboxSelectMultiple)
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['field_name'].widget.attrs['class'] = 'input-block-level'
self.fields['field_name'].choices = self._get_choices()
def _get_choices(self):
return [(val.data1, val.data2) for val in Model.objects.filter()]