If you have a model with foreign key to User, you can use this manager to show (i.e. in admin interface) only objects, that are related to currently logged-in user. Superuser sees all objects, not only his.
Requires: ThreadlocalsMiddleware
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 | class UserManager(models.Manager):
def __init__(self, *args):
try:
self.fk_field_name = args[0]
except IndexError:
self.fk_field_name = None
super(UserManager, self).__init__()
def get_query_set(self):
query_set = super(UserManager, self).get_query_set()
if self.fk_field_name:
current_user = get_current_user()
if current_user and not current_user.is_superuser:
return query_set.filter(**{ '%s__exact' % self.fk_field_name: current_user })
return query_set
# Example usage
class TestModel(models.Model):
owner = models.ForeignKey('auth.user')
objects = UserManager('owner')
|
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
Please login first before commenting.