views:

26

answers:

1

In my django admin section, I'd like to show different versions of the admin page depending on what kind of user is currently logged in. I can think of a couple ways this might work, but haven't figured out how to do any of them.

Perhaps I could put logic into the admin.ModelAdmin to look at the current user and change the 'exclude' field dynamically. Does that work? Or maybe run different custom templates based on who's logged in, and have the templates include / exclude the fields as appropriate.

I could register two versions of the admin.ModelAdmin class, one for each type of user, and maybe restrict access through permissions? But the permissions system seems to believe fairly deeply in one set of permissions per model class so I'm not sure how to change that.

I could grab a couple of the widgets that are used in rendering the admin page templates, and include them in my own page that does the one specific job I need powerful users to be able to do.

I could set up multiple AdminSites and restrict access to them through the url / view system. But then I'm not sure how to register different admin.ModelAdmin classes with the different AdminSites.

Any advice on this would be appreciated.

Answer

Thanks for the hint. Here's how I did it...

def get_form(self, request, obj=None, **kwargs):
    """This dynamically inserts the "owners" field into the exclude list
    if the current user is not superuser.
    """
    if not request.user.is_superuser:
        if self.exclude:
            self.exclude.append('owners')
        else:
            self.exclude = ['owners']
    else:
        # Necessary since Admin objects outlive requests
        try:
            self.exclude.remove('owners')
        except:
            pass


    return super(OwnersModelAdmin,self).get_form(request, obj=None, **kwargs)
+1  A: 

There are quite a few hooks provided in the ModelAdmin class for this sort of thing.

One possibility would be to override the get_form method. This takes the request, as well as the object being edited, so you could get the current user from there, and return different ModelForms dependent on the user.

It's worth looking at the source for ModelAdmin - it's in django.contrib.admin.options - to see if overriding this or any other other methods might meet your needs.

Daniel Roseman
Thanks. That helped. I'm including my code in the question above for reference.
Leopd