0

I try something with readonly field in Django 1.8.7, let say I have some code like the following:

class MyAdmin(admin.ModelAdmin):
    readonly_fields = ('a', 'b')

    def get_readonly_fields(self, request, obj=None):
        if not request.user.is_superuser:
            self.readonly_fields += ('c')
        return super(MyAdmin, self).get_readonly_fields(request, obj)

first I login with super admin and access that admin page change_form,

the code is works well, then I login with staff user, then still works well, again, I try login with superadmin, but the read only fields rendered is for the non-superadmin user,

again I clear the browser cache, try again with super admin, but still not work correctly. I try restart the server, then it work normally until I repeat the same step above I do, this weird thing come again.

Anyone know why this happen ? I think this is looks like some bug but not sure.

Thanks in Advance.

Dev1410
  • 43
  • 3

1 Answers1

2

The bug is not in Django, but in your code. In your get_readonly_fields method you modify the readonly_fields attribute; those modifications persist, since the admin object lives for the lifetime of the process.

Don't do that. get_readonly_fields is supposed to return a value, not modify the attribute. Just do:

def get_readonly_fields(self, request, obj=None):
    rfo = super(MyAdmin, self).get_readonly_fields(request, obj)
    if not request.user.is_superuser:
        rfo += ('c')
    return rfo
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • Nice answer!!! Thanks a lot. I don't see if my code is buggy, then you proof it. thanks for your description about this. – Dev1410 Aug 24 '16 at 12:26