Login

User manager

Author:
diverman
Posted:
July 12, 2009
Language:
Python
Version:
1.0
Tags:
user user-foreign-key users manager owner filter queryset foreignkey
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. Improved generic foreign key manager 2 by Nomalz 5 years, 7 months ago
  2. Querying on existence of a relationship by ubernostrum 7 years, 9 months ago
  3. update primary key (and cascade to child tables) by guettli 3 years, 3 months ago
  4. Specify a manager for the Admin by kylefox 7 years, 3 months ago
  5. improved generic foreign key manager by carljm 6 years, 8 months ago

Comments

Please login first before commenting.