0

I'm new to Django, so I may be completely off track here...

I've seen a lot of questions about being able to access the current user when an object is saved, but my problem is slightly different: I'd like to use (a special subclass of) admin to show a user sets of objects, but only those object he or she has access to.

At the moment I am attempting to do this by creating a special "OpAdmin" app, whose sole purpose is to have this specialized admin. An OpAdmin model looks something like this:

class OperatorAircraftManager(models.Manager):  
    def get_query_set(self, user):
        return mainapp.models.Aircraft.objects.filter(owner=user.employer)

class Aircraft(mainapp.models.Aircraft):
    class Meta:
        proxy = True
    objects = OperatorAircraftManager()

But I am having a hard time getting my head around how I would pass the user information to get_query_set, or whether this is the wrong approach entirely (should I be doing something with Groups or Permissions instead?) Again, this is not about saving the user info with a new Aircraft, or restricting who can change one, but about restricting who can see them in admin. Any suggestions would be appreciated --- thanks.

Edit: I should add that I have also seen a number of "get current user" packages for use with Django, but they all seem a bit hacky (looking on the current call stack for example), so I've been reluctant to go that route. If there is an accepted way to cache some shared information about the request context, that would be good to know...

4

1 回答 1

4

不确定您所说的“只有他或她可以访问的那些对象”是什么意思。但是,如果您想在管理员中将所有对象限制为各自的所有者,您可以这样做:

def queryset(self, request):
    """Limit Pages to those that belong to the request's user."""
    qs = super(PageAdmin, self).queryset(request)
    return qs.filter(owner=request.user)
于 2013-08-07T02:39:57.883 回答