Filter admin inlines

25 views
Skip to first unread message

NENAD CIKIC

unread,
Feb 5, 2012, 7:43:06 AM2/5/12
to django...@googlegroups.com
Hello,
I have three models
X
Lang
Y
where the purpose of Y is to provide X fields in other languages.
So I have Y as
Y
x foreignkey on X
lang ForeignKey on Lang
additionalfields...

I have created the ModelAdmin for Lang. For X I have the ModelAdmin and added the
    inlines = [
        YInline,
        ]

So far so good: I have the form of X with inlines for Y with a dropdown on languages.
Now I have extended the user profile as documented in django docs. I have succesfully overriden the queryset method ot he LangModelAdmin so to filter on some user profile additinal information.
The problem is that I can not filter the inlines; i.e. I want that every user has its owns languages and thus I want to see in X form the language dropdown filled with only certain languages. Instead all languages are listed there.
I have searched a bit and it seems a common problem,but without solution.
Am I missing something simple?
Thanks


Marc Aymerich

unread,
Feb 5, 2012, 10:07:47 AM2/5/12
to django...@googlegroups.com

As far as I can remember there is no method to overide on admin inline
class in order to queryset filtering. But admin inline classes
provides a form attribut that let you to specify what form to use, so
I think the way to go is providing a custom inline form that performs
the queryset filtering, just like this:
http://stackoverflow.com/questions/2581049/filter-queryset-in-django-inlineformset-factory

--
Marc

NENAD CIKIC

unread,
Feb 5, 2012, 4:47:34 PM2/5/12
to django...@googlegroups.com
Thanks. So to summarize the solution to filter inlines in admin interface based on userprofile was:
define the form on Y model as:

class YForm(forms.ModelForm):
    request=None   #NOTE THIS
    lang=forms.ModelChoiceField(queryset=lang.objects.all()) #first get all

    def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=ErrorList,
                 label_suffix=':', empty_permitted=False, instance=None):
        super(YForm, self).__init__(data, files, auto_id, prefix, initial, error_class, label_suffix,
            empty_permitted, instance)

        self.fields["lang"].queryset = lang.objects.filter(company__exact=self.request.user.get_profile().company)

    class Meta:
        model = Jelo_strani_lang
       
Where Lang model and userprofile has the same field "company" ; i.e. the user is part of that company, and the languages are defined at company level  

Then I have defined the inline as:
class YInline(admin.StackedInline):
    model = Y
    form=YForm
    ordering = ('lang',)

    def get_formset(self, request, obj=None, **kwargs):
        self.form.request=request  #NOTE THIS
        return super(YInline, self).get_formset(request, obj, **kwargs)
       
 Hope that helps to someone
Reply all
Reply to author
Forward
0 new messages