Restricting admin fieldsets for non-superusers

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class RestrictedUserAdmin(UserAdmin):
    declared_fieldsets = None
    restricted_fieldsets = (
        (None, {'fields': ('username', 'password')}),
        (_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}),
    )

    def queryset(self, request):
        if request.user.is_superuser:
            return User.objects.all()
        return User.objects.filter(id__exact=request.user.id)

    def get_fieldsets(self, request, obj=None):
        if request.user.is_superuser:
            return super(UserAdmin, self).get_fieldsets(request, obj)
        return self.restricted_fieldsets

    def get_form(self, request, obj=None, **kwargs):
        """
        Workaround bug http://code.djangoproject.com/ticket/9360 (thanks to peritus)
        """
        return super(UserAdmin, self).get_form(request, obj, fields=flatten_fieldsets(self.get_fieldsets(request, obj)))

admin.site.unregister(User)
admin.site.register(User, RestrictedUserAdmin)

More like this

  1. Restrict Flatpage To Group by nikolaj 6 years ago
  2. Restrict staff access to admin pages by slink 3 years, 6 months ago
  3. View all log entries in the admin by jakub 2 years, 9 months ago
  4. User manager by diverman 4 years, 9 months ago
  5. Anonymous required decorator by Motanelu 4 years, 3 months ago

Comments

phretor (on October 13, 2009):

This avoids some issues (especially in Django 1.1) and follows the philosophy of the super class. In particular, it honors the following check:

if self.declared_fieldsets:
    fields = flatten_fieldsets(self.declared_fieldsets)
else:
    fields = None

class RestrictedUserAdmin(UserAdmin):
    declared_fieldsets = None
    restricted_fieldsets = (
        (None, { 'fields': ('username', 'password') }),
        (_('Personal info'), { 'fields': ('first_name', 'last_name', 'email') }),
    )

    def queryset(self, request):
        if request.user.is_superuser:
            return User.objects.all()
        return User.objects.filter(id__exact=request.user.id)

    def get_fieldsets(self, request, obj=None):
        if request.user.is_superuser:
            return super(UserAdmin, self).get_fieldsets(request, obj)
        return self.restricted_fieldsets

    def get_form(self, request, obj=None, **kwargs):
        if not request.user.is_superuser:
            self.declared_fieldsets = self.restricted_fieldsets
        return super(UserAdmin, self).get_form(request, obj)

#

(Forgotten your password?)