define the queryset of ModelMultipleChoiceField in

2019-08-15 05:23发布

I'm using ModelMultipleChoiceField with a large number of objects. I want to show only the selected objects and let the user remove a choice with js. To add choices the user will open a popup similar to ManyToManyRawIdWidget.

I can limit the queryset to the selected choices in the init of the form with:

def __init__(self, *args, **kwargs):        
    super(FormName, self).__init__(*args, **kwargs)
    self.fields['field_name'].queryset = self.instance.field_name

But this will require manual setting on every form. Is it possible to extend the ModelMultipleChoiceField to get the queryset from the field choices? I think that I need to extend ModelChoiceIterator but couldn't understand how to access the module instance.

Thanks

1条回答
闹够了就滚
2楼-- · 2019-08-15 05:56

i am not sure if this is what you are looking for, but if you want the same "list-shuttle" than in auth/user/permissions you should try this;

class MyForm(forms.ModelForm):
    myfield = forms.ModelMultipleChoiceField(
        queryset = Category.objects.all(),
        widget = admin.widgets.FilteredSelectMultiple(
                _('myfield'), False),
        required = False,
    )

class MyAdmin(admin.ModelAdmin):

   form = MyForm   
查看更多
登录 后发表回答