Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django admin - group permissions to edit or view models

Tags:

python

django

I'm searching for a way to customize the Django Administration to support permissions based on the user group.

For example, I've just created the Developers group, now I've also created the Tickets model, with AdminModel to specify how to list data.

I'd like to have this model visible only by Developers, and hidden to each other not in this group (eg filter the view based on groups). I've read a lot of documentations, but couldn't really find and understand what to do to have it working.

For security purposes I'd also need to check user groups at runtime when adding-deleting objects for a specific model (the one I've hidden to people outside the Developers group), otherwise it would only need to know the URL to use the model :s

It looks like a simple task, but maybe I'm missing something... any 3rd party middleware, or just a way to do it? I'm also ready to edit the administration views if needed, but I need to know what do to.

Thank you :-)

like image 663
Ale A Avatar asked Dec 05 '11 22:12

Ale A


People also ask

Does Django have view permissions?

The Django admin site uses permissions as follows: Access to view objects is limited to users with the “view” or “change” permission for that type of object. Access to view the “add” form and add an object is limited to users with the “add” permission for that type of object.

How do I use group permissions in Django?

With Django, you can create groups to class users and assign permissions to each group so when creating users, you can just assign the user to a group and, in turn, the user has all the permissions from that group. To create a group, you need the Group model from django. contrib. auth.

How do I restrict access to parts of Django admin?

Django admin allows access to users marked as is_staff=True . To disable a user from being able to access the admin, you should set is_staff=False . This holds true even if the user is a superuser. is_superuser=True .


1 Answers

ModelAdmin has three methods dealing with user permission: has_add_permission, has_change_permission and has_delete_permission. All three should return boolean (True/False).

So you could do something like:

class TicketAdmin(admin.ModelAdmin):
    ...
    def has_add_permission(self, request):
        return request.user.groups.filter(name='Developers').exists()

    def has_change_permission(self, request, obj=None):
        return request.user.groups.filter(name='Developers').exists()

    def has_delete_permission(self, request, obj=None):
        return request.user.groups.filter(name='Developers').exists()

When False is returned from one of these, it's results in a 403 Forbidden.

like image 74
Chris Pratt Avatar answered Oct 16 '22 07:10

Chris Pratt