在小部件中定义ModelMultipleChoiceField的queryset [英] define the queryset of ModelMultipleChoiceField in the widget

查看:73
本文介绍了在小部件中定义ModelMultipleChoiceField的queryset的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将ModelMultipleChoiceField与大量对象一起使用。
我只想显示选定的对象,并让用户使用js删除选择。
要添加选择,用户将打开类似于ManyToManyRawIdWidget的弹出窗口。

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.

我可以将查询集限制为 init 的形式:

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

但这需要在每个表格上进行手动设置。
是否可以扩展ModelMultipleChoiceField以从字段选择中获取查询集?
我认为我需要扩展ModelChoiceIterator,但不了解如何访问模块实例。

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.

谢谢

推荐答案

我不确定这是否是您要寻找的东西,但是如果您要使用与auth / user / permissions中相同的 list-shuttle,则应尝试此操作;

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   

这篇关于在小部件中定义ModelMultipleChoiceField的queryset的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆