使用ModelForm并传递参数

时间:2009-03-13 22:13:22

标签: django django-models django-forms

class MyUserAdminForm(forms.ModelForm):
class Meta:
    model = Users

group = forms.ModelMultipleChoiceField(
    queryset=Groups.objects.filter(domain__user=3),
    widget=forms.CheckboxSelectMultiple,
)

class UserAdmin(admin.ModelAdmin):

list_display = ('login', 'company', 'userType')
form = MyUserAdminForm
filter_horizontal = ('group',)


admin.site.register(Users, UserAdmin)

我正在使用MyUserAdminForm来自定义管理界面。我必须将User表的pk作为参数传递给过滤器

queryset=Groups.objects.filter(domain__user=3)

我应该传递User表的pk而不是硬编码的'3'。 想知道如何实现这一目标?

1 个答案:

答案 0 :(得分:1)

正在编辑的对象被赋予instance参数中表单的构造函数。您应该可以使用它来过滤组选择:

class MyUserAdminForm(forms.ModelForm):
    class Meta:
        model = Users

    group = forms.ModelMultipleChoiceField(
            queryset=Groups.objects.all(),
            widget=forms.CheckboxSelectMultiple,
    )

    def __init__(self, *args, **kwargs):
        super(MyUserAdminForm, self).__init__(*args, **kwargs)
        if kwargs.has_key('instance'):
            qs = Group.objects.filter(domain__user=kwargs['instance'].pk)
            self.fields['group'].queryset = qs