1

UPDATE: Looks like I will have to create custom widget (Grouping CheckboxSelectMultiple Options in Django). Will include the final code when I'm done.

I have set up a choice field in a django form similar to another SO question.

However, I would like to make it a CheckboxSelectMultiple widget, but doing so in the class Meta creates a checkbox for the entire group. Is this something I need to do in the __init__, if so how?

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'
Community
  • 1
  • 1
snakesNbronies
  • 3,619
  • 9
  • 44
  • 73

3 Answers3

1

I assume you are using modelForm.

You can modify the fields in init

Here is how:

class SomethingForm(forms.modelForm):
    def __init__(self, *args, **kwargs):
        super(SomethingForm, self).__init__(*args, **kwargs)
        self.field['myfieldname'] = forms.CharField(
                                    widget=forms.HiddenInput)
  • That didn't do it for me. I'm wondering if I need to make subwidgets or somehow change the iwdget at the 'self.fields['myField'].choices' level – snakesNbronies Jan 30 '13 at 15:54
0

Looks like creating a custom widget was the way to go - as per Grouping CheckboxSelectMultiple Options in Django

NOTE: I removed the iterator as per How to group the choices in a Django Select widget?

Community
  • 1
  • 1
snakesNbronies
  • 3,619
  • 9
  • 44
  • 73
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()]
catherine
  • 22,492
  • 12
  • 61
  • 85