Make field in admin read only dependent on user

302 views Asked by At

I am trying to give a staff user change access to only his own user record in the django admin but to also have readonly view of the records of the other staff users. I could easily do this by defining the fields in the get_readonly_fields method. But whenever I add a field to the model I have to add this there too (and if I forget its big trouble).

So I tried this (found somewhere at SO):

def get_readonly_fields(self, request, obj=None):
    my_readonly_fields= list(set([field.name for field in self.opts.local_fields] 

However, this will make excluded fields reappear (it seams that readonly fields are always shown) which I do not want.

Is there a way to get the valid fields? The get_fields method I cannot call, because it will try to call the get_readonly_fields method. Or is there a generally better way to do this?

1

There are 1 answers

2
Wolph On

Assuming you're not using ModelAdmin.get_fields or ModelAdmin.get_fieldsets to generate the list of fields, you can just walk through the self.fields or self.fieldsets and exclude those from the readonly_fields list.

Specifically:

def get_readonly_fields(self, request, obj=None):
    my_readonly_fields = [
        field.name
        for field in self.opts.local_fields
        if field.name not in self.fields]

    return list(set(my_readonly_fields))