Wednesday, February 29, 2012

Re: Keeping filters when adding in the admin interface

On Wed, Feb 29, 2012 at 10:55 PM, Marc Aymerich <> wrote:
> On Wed, Feb 29, 2012 at 8:22 PM, Mauro Sánchez <> wrote:
>> Hello, if I have the following Model:
>> class A:
>>    name
>> class B:
>>    name
>>    a = models.ForeignKey(A)
>> class C:
>>    name
>>    b = models.ForeignKey(B)
>> And let's suppose that in the Admin Site I have a Filter in the C list
>> that refers to the A model. Is there a way to keep that filter when I
>> am going to add a new C object and use it to filter the combobox of
>> the b filed so that it will only show the b objects that are related
>> to the A model in the filter?
>> For example:
>> If the filter I choose points to the id=1 in the A model, the combobox
>> for the b field when I add a C object only has to show the B objects
>> that has a = 1
> If I understand you righ, it's a bit triky stuff, you have to do two things:
> 1)  Define a custom add_form and override their __init__ method with
> something like:
>  self.fields['b'].queryset = self.fields['b'].queryset.filter(a=a_pk)
> 2)  Provides the current value of your filter (a_pk) to the defined form on 1)
>  I think this can be done overriding modeladmin.get_form() method
> since request is one of their args, so you can extract the value of
> the filter on the http referer url and provide it to the form that
> this method creates.

More specifically:

def get_form(self, request, *args **kwargs):
form = super(YourModelAdmin, self).get_form(request, *args, **kwargs)
a_pk = get_a_pk_from_http_referer(request)
form.a_pk = a_pk
return form

def __init__(self, *args, **kwargs):
super(YourModelForm, self).__init__(*args, **kwargs)
self.fields['b'].queryset = self.fields['b'].queryset.filter(a=self.a_pk)


You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to
To unsubscribe from this group, send email to
For more options, visit this group at

No comments:

Post a Comment