3

I want to exclude some fields in my inline based on my request user.

I know somehow I can handle this with methods like 'get_formsets', 'add_view', 'change_view', but I'm not sure what the syntax is.

Any suggestions?

monkeyBug
  • 555
  • 1
  • 4
  • 16

2 Answers2

4

I achieved what I needed with the next code in my inline class:

def get_formset(self, request, obj=None, **kwargs):
        if request.user.groups.all().count() > 0:
            if request.user.groups.all()[0].name == 'User Group Name':
                kwargs['exclude'] = ['field_to_exclude',]
        return super(MyInline, self).get_formset(request, obj, **kwargs)

The answer to this question gave me the hints: different fields for add and change pages in admin

Community
  • 1
  • 1
monkeyBug
  • 555
  • 1
  • 4
  • 16
2

There's also the get_exclude hook:

class FoodInline(TabularInline):
    model = Food

    def get_exclude(self, request, obj=None):
        group = request.user.groups.first()

        if group and group.name == 'User Group Name':
            return ['field_to_exclude', ]

        return self.exclude
Matt
  • 8,758
  • 4
  • 35
  • 64