[ACCEPTED]-Object Ownership in Django-django
My approach would be adding a method to 17 the model:
class YourModelWithOwnership(models.model): ... def user_can_manage_me(self, user): return user == self.user or user.has_perm('your_app.manage_object')
I'd then call that method whenever 16 a permission check is required, and take 15 some action based on the outcome. So for 14 a view that would be
from django.shortcuts import get_object_or_404 ... def view_func(request, item_id): item = get_object_or_404(YourModelWithOwnership, id=item_id) # or whatever is needed to get the object if not item.user_can_manage_me(request.user): # user not allowed to manage ... else: ...
Later I'd probably realize 13 that that's still quite some boilerplate 12 code to write in every view that needs that 11 test, so I'd implement an exception that's 10 thrown when a user can't manage an object...
class CannotManage(Exception): pass
...and 9 add another method to the model:
from django.db import models from django.shortcuts import get_object_or_404 class YourModelWithOwnership(models.model): ... @classmethod def get_manageable_object_or_404(cls, user, *args, **kwds): item = get_object_or_404(cls, *args, **kwds) if not item.user_can_manage_me(user): raise CannotManage return item
Then, in 8 the view functions, this can be used:
def view_func(request, item_id): item = YourModelWithOwnership.get_manageable_object_or_404(request.user, id=item_id) ...
This 7 will of course raise an exception when the 6 user isn't the owner and does not have the 5 proper permission. That exception can be 4 handled in the
process_exception() method of a custom middleware class so that 3 there's a single handler for all instances 2 where a user is not allowed to mess with 1 the object.
A while back I wrote up the usual technique for doing this in the admin. You may want to 2 read through that to see how the implementation 1 works.
You can look into RowLevelPermissions branch. It hasn't been 2 included even in 1.1 beta though, I guess 1 it still needs some development.
More Related questions