Filtering foreignkey fields in django admin

1
2
3
4
5
6
7
8
class MyAdmin(admin.ModelAdmin):
    def get_form(self, request, obj=None, **kwargs):
        form = super(MyAdmin,self).get_form(self,request, obj,**kwargs)
        # form class is created per request by modelform_factory function
        # so it's safe to modify
        #we modify the the queryset
        form.base_fields['foreign_key_field].queryset = form.base_fields['foreign_key_field].queryset.filter(user=request.user)
        return form

More like this

  1. Changelist filter by ForeignKey by overclocked 3 years, 5 months ago
  2. ForeignKey filterspec by luc_j 3 years, 7 months ago
  3. Custom change_list filter based on SimpleListFilter shows only referenced (related, used) values by darklow 1 year, 2 months ago
  4. RelatedNullFilterSpec: django-admin custom filter all/null/not null/choices by Codeko 3 years, 6 months ago
  5. Limit ForeignKey filter values to those that have a relationship with current model by overclocked 3 years, 5 months ago

Comments

dave.leblanc (on December 6, 2012):

Thanks for the snippet was exactly what I was looking for

I found a couple typos in implementing a revised example is below

class MyAdmin(admin.ModelAdmin):
    def get_form(self, request, obj=None, **kwargs):
        form = super(MyAdmin,self).get_form(request, obj,**kwargs)
        # form class is created per request by modelform_factory function
        # so it's safe to modify
        #we modify the the queryset
        form.base_fields['foreign_key_field'].queryset = form.base_fields['foreign_key_field'].queryset.filter(user=request.user)
        return form

#

(Forgotten your password?)