Permission Based Django admin filter strings

In a Django admin, I would like to display only specific rows of a user-based model.

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

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

+4
source share
2 answers

I think you need a set of ModelAdmin requests:

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 

It is assumed that the user is tied to a location through a profile model.

+6
source

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) 
+1
source

All Articles