0
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 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.