Django Admin: Restrict staff to update

Viewed 428

I had a Blog Model. All new blog post has DRAFT status.

In the admin page, admin would be all permissions (CRUD) on the Blog Model. I can solve this by using Django's register method.

What I want is is_staff user can view all the Blog Post but can't update Status (Eg. from DRAFT to APPROVE).

Is there any way to check the request's group, then allow the user to update or not? Thanks.

1 Answers

The simplest solution is to mark the status field as read only in the admin class, by setting readonly_fields:


from django.contrib import admin
from .models import BlogPost

@admin.register(BlogPost):
class BlogPostAdmin(admin.ModelAdmin):
    readonly_fields = ('status',)

Note that this makes status read-only for ALL admin users. If you need more fine-grained control based on the current user, there is a get_readonly_fields method you can override.

Also, since ALL users of the Django Admin have is_staff, we'll explicitly check for the built-in permission to change a BlogPost.

class BlogPostAdmin(admin.ModelAdmin):
    def get_readonly_fields(self, request, obj=None):
        # obj is None if we're creating a new BlogPost, or a BlogPost instance
        # if we are editing an existing BlogPost
        if not request.user.has_perm("your_app.change_blogpost"):
            return ("status",)
        return []
Related