Django Admin - Allow models to be shown for is_staff users

删除回忆录丶 提交于 2021-02-08 21:41:08

问题


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


回答1:


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




回答2:


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.




回答3:


The staff_member_required decorator

staff_member_required(redirect_field_name='next', login_url='admin:login') [source]

This decorator is used on the admin views that require authorization. A view decorated with this function will having the following behavior:

If the user is logged in, is a staff member (User.is_staff=True), and is active (User.is_active=True), execute the view normally.

Otherwise, the request will be redirected to the URL specified by the login_url parameter, with the originally requested path in a query string variable specified by redirect_field_name. For example: /admin/login/?next=/admin/polls/question/3/.

Example usage:

from django.contrib.admin.views.decorators import staff_member_required

@staff_member_required
def my_view(request):
    ...


来源:https://stackoverflow.com/questions/34565676/django-admin-allow-models-to-be-shown-for-is-staff-users

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!