Is there a way to do row level permissions in django? I thought there wasn\'t but just noticed this in the docs:
Permissions can be set not only per type
The methods that the docs talk about will allow you to restrict access to particular objects in the admin. Each method is passed the object in play, which you can use to make determinations about whether a user can access it, by returning either True
or False
.
class MyModelAdmin(admin.ModelAdmin):
...
def has_add_permission(self, request):
# This one doesn't get an object to play with, because there is no
# object yet, but you can still do things like:
return request.user.is_superuser
# This will allow only superusers to add new objects of this type
def has_change_permission(self, request, obj=None):
# Here you have the object, but this is only really useful if it has
# ownership info on it, such as a `user` FK
if obj is not None:
return request.user.is_superuser or \
obj.user == request.user
# Now only the "owner" or a superuser will be able to edit this object
else:
# obj == None when you're on the changelist page, so returning `False`
# here will make the changelist page not even viewable, as a result,
# you'd want to do something like:
return request.user.is_superuser or \
self.model._default_manager.filter(user=request.user).exists()
# Then, users must "own" *something* or be a superuser or they
# can't see the changelist
def has_delete_permission(self, request, obj=None):
# This pretty much works the same as `has_change_permission` only
# the obj == None condition here affects the ability to use the
# "delete selected" action on the changelist