Django使用CheckboxSelectMultiple小部件形成选择组

时间:2013-01-30 15:17:33

标签: django forms django-forms

更新:看起来我必须创建自定义小部件(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'

3 个答案:

答案 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)

根据Grouping CheckboxSelectMultiple Options in Django

,似乎可以创建自定义小部件

注意:我按照How to group the choices in a Django Select widget?

删除了迭代器

答案 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()]