visitor1
visitor1

Reputation: 33

How to filter admin options by a user attribute?

I have a model with a foreing key to a model called Country.

Each time I edit my model in the admin, when diplaying the country option I see a lot of contries. I'd like that option list to be pre filtered by a user attribute (user.get_profile().continent for example).

Where can I hook it?

Thanks

Upvotes: 0

Views: 631

Answers (1)

Danny W. Adair
Danny W. Adair

Reputation: 12978

Check http://docs.djangoproject.com/en/dev/ref/contrib/admin/ - "ModelAdmin.formfield_for_choice_field()"

class MyModelAdmin(admin.ModelAdmin):
    def formfield_for_choice_field(self, db_field, request, **kwargs):
        if db_field.name == "country":
            kwargs['choices'] = get_country_choices_for_continent(request.user.get_profile().continent)
        return super(MyModelAdmin, self).formfield_for_choice_field(db_field, request, **kwargs)

Upvotes: 1

Related Questions