Django admin: how to hide fields for certain users (that are not superusers)

Posted on the April 8th, 2010 under Django, Programming, Python by Mauro

I’m working on a project and I’m using the incredible django admin. So, yesterday I needed a way to hide some fields in a model for user that didn’t have superuser permissions. After some googling, I found a method in the ModelAdmin class that was perfect (well, I think that it’s perfect) for my needs: get_form.
The method is not really mentioned in the official django documentation except in the comment framework, but you can use it in your ModelAdmin subclass as well. It’s called before the “change form” is created, so we can dynamically change it before it’s displayed.
The principle is very simple: I dynamically populate the exclude attribute so that if a user is not a superuser I can exclude a field (or more that one field). Let’s see an example:

class MyModelAdmin(admin.ModelAdmin):
	def get_form(self, request, obj=None, **kwargs):
		self.exclude = []	
		if not request.user.is_superuser:
			self.exclude.append('field_to_hide')
		return super(MyModelAdmin, self).get_form(request, obj, **kwargs)

What it does is simply add the field_to_hide to the exclude list of MyModelAdmin. In this case, the field will be visible only to superusers, checking the request.user.is_superuser attribute. Pretty simple!

Donate 1 euro, buy me a coffee, I need it to write more posts! Thanks ;)

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Furl
  • Netvibes
  • Pownce
  • Reddit
  • StumbleUpon
  • Technorati
  • TwitThis
  • LinkedIn
  • Ma.gnolia
  • MySpace
Tags: , , , ,

Leave a Reply




XHTML::
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">