Search code examples
djangodjango-admindjango-admin-filters

Django admin filter rows based on permissions


In the Django admin, I would like to display only certain rows of a model based on the user.

class Article(models.Model):
    text =          models.TextField(max_length=160)
    location =        models.CharField(max_length=20)

So, when a user logs into the admin site, and is part of the San Francisco location, they should only be able to see Articles with that location.


Solution

  • I think what you want is ModelAdmin's queryset:

    https://docs.djangoproject.com/en/1.4/ref/contrib/admin/#django.contrib.admin.ModelAdmin.queryset

    class ArticleAdmin(admin.ModelAdmin):
        def queryset(self, request):
            qs = super(ArticleAdmin, self).queryset(request)
            if request.user.profile.location: # If the user has a location
                # change the queryset for this modeladmin
                qs = qs.filter(location=request.user.profile.location)
            return qs
    

    This assumes the user is tied to a location via a profile model.