Login

Filtering foreignkey fields in django admin

Author:
forgems
Posted:
June 9, 2009
Language:
Python
Version:
1.0
Score:
3 (after 5 ratings)

Sometimes you need to filter foreignkey choices in admin interface, to objects created by user or meeting some other condition. In django 1.0 there is no formfield_for_foreignkey method in ModelAdmin class so we have to make a workaround. Here is the solution I have found to be the easiest for me.

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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 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

#

Shafeenes (on January 16, 2020):

hello sir where should i paste this file in and what modification should i do my my files

#

Please login first before commenting.