views:

307

answers:

1
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)

I am using MyUserAdminForm for customizing the admin interface. I have to pass the pk of the User table as the argument to the filter

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

I should pass the pk of the User table instead of the hard coded '3'. Wanted to know how this can be achieved?

+1  A: 

The object being edited is given to the form's constructor in the instance argument. You should be able to use that to filter the group choices:

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
Guðmundur H