User Specific Data in Admin

October 2, 2010

Building on the last post (, I wanted to allow some users to be able to see the full list of records for their SITE_ID, and others to be limited to just the records they had created.

Each model object had a owner field, so the select was trivial, but I needed to be able to limit the data shown in a generic manner.

Here's the model as used in the previous example, but modified to add the owner field:

class AudioEvent(models.Model):
    # ...
    owner = models.ForeignKey(User, editable=False, related_name='AudioEventOwner')
    site = models.ForeignKey(Site,default=Site.objects.get_current().id,editable=False)
    objects = models.Manager()
    on_site = CurrentSiteManager()

In, we're going to change the queryset method to use a superclass method instead of doing the select manually:

class AudioEventAdmin(SiteOnlyAdmin):
    def queryset(self,request):
        return self.limit_queryset(request, AudioEvent)


In the SiteOnlyAdmin class we're going to define limit_queryset like this:

def limit_queryset(self, request, pObject):
    Limit the list of objects shown to the user. 
    If the user is the siteadmin show objects on the current site are shown
    If the user isn't the siteadmin, then just show ones that they own
    lCurrentSite = Site.objects.get_current()
    lSiteAdmin = SiteData.objects.filter(site_owner=request.user).filter(site=lCurrentSite).count()
    lSecondaryAdmin = request.user.has_perm('members.secondary_admin')

    if lSiteAdmin or lSecondaryAdmin:
        return pObject.on_site.all()
        return pObject.on_site.filter(owner=request.user)

SiteData is a normal Django model object that defines which user is the owner of a particular site. The user is an admin if they are in this table, or have a specific permission. If a user is an admin, we return all the rows for the current site. If they're not, we limit the list to the ones the user is recorded as owner for.