Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Admin - Allow models to be shown for is_staff users

I need to make some Django models available for is_staff=True users in the Django admin interface. I do not want to go for each user and assign them permissions or group permissions to the staff users.

Which method do I need to override in ModelAdmin or BaseModelAdmin class or is there any other simpler way? I am using Django 1.4 Version

like image 852
SiddharthG Avatar asked Feb 08 '23 03:02

SiddharthG


2 Answers

class TeacherAdmin(admin.ModelAdmin):
    def has_add_permission(self, request):
        return True
    def has_change_permission(self, request, obj=None):
        return True
    def has_module_permission(self, request):
        return True

has_module_permission checks if the model can be listed in the app labels table

like image 173
jimmymeego Avatar answered Feb 24 '23 10:02

jimmymeego


Something like this should work:

class StaffRequiredAdminMixin(object):

    def check_perm(self, user_obj):
        if not user_obj.is_active or user_obj.is_anonymous():
            return False
        if user_obj.is_superuser or user_obj.is_staff:
            return True
        return False

    def has_add_permission(self, request):
        return self.check_perm(request.user)

    def has_change_permission(self, request, obj=None):
        return self.check_perm(request.user)

    def has_delete_permission(self, request, obj=None):
        return self.check_perm(request.user)

and all ModelAdmin(s) should inherit this class. For example:

class MyModelAdmin(StaffRequiredAdminMixin, admin.ModelAdmin):
    pass

admin.site.register(MyModel, MyModelAdmin)

Please note, this code is untested.

like image 45
mishbah Avatar answered Feb 24 '23 10:02

mishbah