4

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.

4

2 回答 2

6

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.

于 2012-08-10T21:41:18.400 回答
1

Use has_add_permission, has_change_permission and has_delete_permission with a custom ModelAdmin (in admin.py):

class ArticleAdmin(admin.ModelAdmin):
    def has_add_permission(self, request):
        # Nothing really to do here, but shown just to be thorough
        return super(ArticleAdmin, self).has_add_permission(request)

    def has_change_permission(self, request, obj=None):
        if obj is not None:
            return obj.location == request.user.get_profile().location
        else:
            return super(ArticleAdmin, self).has_change_permission(request, obj=obj)

    def has_delete_permission(self, request, obj=None):
        if obj is not None:
            return obj.location == request.user.get_profile().location
        else:
            return super(ArticleAdmin, self).has_delete_permission(request, obj=obj)
admin.site.register(Article, ArticleAdmin)
于 2012-08-10T20:53:00.750 回答