在Django管理员中,我想根据用户只显示模型的某些行。
class Article(models.Model):
text = models.TextField(max_length=160)
location = models.CharField(max_length=20)
因此,当用户登录管理网站并且是旧金山location
的一部分时,他们应该只能看到Articles
该位置。
答案 0 :(得分:6)
我认为你想要的是ModelAdmin的查询集:
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
这假设用户通过配置文件模型绑定到某个位置。
答案 1 :(得分:1)
使用has_add_permission
,has_change_permission
和has_delete_permission
与custom ModelAdmin
(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)