Deepankar Bajpeyi
Deepankar Bajpeyi

Reputation: 5879

Construct form from queryset

I have a queryset in a particular view :

class SomeView(View)
    def get(self, request, *args, **kwargs):
        objs = SomeModel.objects.all()

Now I somehow want this to be displayed as a form of objs with checkboxes.

Also the queryset might not be SomeModel.objects.all() always. It might change in the view depending on the request.

Which is the best way to achieve this ?

Upvotes: 0

Views: 39

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599956

This is what the ModelMultipleChoiceField does. You can use it in conjunction with the CheckboxSelectMultiple widget to get what you want.

class MyForm(forms.Form):
    my_choices = forms.ModelMultipleChoiceField(
                      queryset=SomeModel.objects.all(),
                      widget=forms.CheckboxSelectMultiple)

Edit

To change the queryset depending on a value, you need to override __init__:

def __init__(self, *args, **kwargs):
    model_value = kwargs.pop('my_value', None)
    super(MyForm, self).__init__(*args, **kwargs)
    if model_value is not None:
        self.fields['my_choices'].queryset = SomeModel.objects.filter(my_field=my_value)

Upvotes: 1

Related Questions