Reputation: 25233
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.
Upvotes: 4
Views: 3557
Reputation: 10939
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.
Upvotes: 6
Reputation: 239460
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)
Upvotes: 1