What is the best way to create select form for multiple object dynamically in Django

Refresh

March 2019

Views

68 time

1

I have some objects lets say foo1,foo2,foo3,foo4 .. etc.

I want to create a form where I can select any one of these foo objects. I can do this in a few ways.

1)

 class FooReportForm(forms.Form):
    foo = forms.CheckboxInput()
    def __init__(self,*args,**kwargs):
        foos= kwargs.get('foos')
        foo_choice = []
        for foo in foos:
            index = (foo.id,foo.name +" Area"+foo.area+" Region"+foo.region )
            foo_choice.append(index)

        super( PropertyReportForm, self).__init__(*args, **kwargs)
        self.fields['foo'].choices = foo_choice`

2) `

class FooForm(forms.Form):
    def __init__(self, *args, **kwargs):
        foos= kwargs.pop('foos')
        super(FooForm, self).__init__(*args, **kwargs)
        choices = []
        if foos:
            pass
        else:
            foos = []
        for i,fooin enumerate(foos):
            index = [(foo.id , foo)]
            choices = index
            self.fields['foo_%s'% i] = forms.MultipleChoiceField(choices=choices,widget =forms.CheckboxSelectMultiple,required = False)

The first approach does not allow me to check or uncheck some options first. How can I do this in this approach? The second one is wrong cause it creates a new field for every choice. What is the best way to do this ?

1 answers

2

you can use the Model Multiple Choice Field with the Checkbox Select Multiple Widget.

foos = forms.ModelMultipleChoiceField(queryset=Foo.objects, widget=forms.CheckboxSelectMultiple())