Login

User manager

Author:
diverman
Posted:
July 12, 2009
Language:
Python
Version:
1.0
Score:
2 (after 2 ratings)

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

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 9 months, 4 weeks ago
  5. Help text hyperlinks by sa2812 10 months, 3 weeks ago

Comments

Please login first before commenting.