A mixin to define permissions on models. This is more of an abstract model to subclass/customise than a plug-in solution. Explanations are here.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | from django.contrib.auth.models import User
class PermissionError(StandardError):
pass
class PermissionMixin(object):
def attempt(self, action, actor, msg=None):
return PermissionMixin._attempt(self, action, actor, msg=None)
@classmethod
def cls_attempt(cls, action, actor, msg=None):
return PermissionMixin._attempt(cls, action, actor, msg=None)
@staticmethod
def _attempt(obj, action, actor, msg):
if actor.__class__ != User or not isinstance(action, basestring):
raise TypeError
if getattr(obj, 'allows_%s_for' % action.lower().replace(' ', '_'))(actor):
return True
else:
if msg is None:
msg = u'%s doesn\'t have permission to %s %s' % (actor.username, action.lower(), repr(obj))
raise PermissionError(msg)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Could you please write how to use your code?
#
Please login first before commenting.