2015-12-11 85 views
0

在django 1.8如何過濾基於登錄用戶的list_filter?我無法使用django.contrib.admin中的SimpleListFilter,因爲我使用django.contrib.admin.apps.SimpleAdminConfig來使用AdminPlus註冊視圖。django1.8基於登錄的過濾器list_filter

一些代碼,我在的ModelAdmin嘗試:

def get_list_filter(self, request): 
    my_list_filter = super(SubCategoryAdmin, self).get_list_filter(request) 
    if request.user.is_superuser: 
     pass 
    else: 
     my_list_filter = self.get_queryset(request) 

    return my_list_filter 

def get_queryset(self, request): 
    ''' 
    Superuser has all permissions. 
    ''' 
    qs = super(SubCategoryAdmin, self).get_queryset(request) 
    if request.user.is_superuser: 
     pass 
    else: 
     qs = qs.filter(
      category__in=Category.objects.filter(
       department__in=Department.objects.filter(
        name=request.user.customuser.department.name))) 
    return qs 

回答

-1

隨後的文檔,並在這裏找到了答案:[https://docs.djangoproject.com/en/1.8/ref/contrib/admin/][1]

分享我的答案是:

class UserCategoryListFilter(admin.SimpleListFilter): 
    # Human-readable title which will be displayed in the 
    # right admin sidebar just above the filter options. 
    title = _('Department',) 

    # Parameter for the filter that will be used in the URL query. 
    parameter_name = 'department' 

    def lookups(self, request, model_admin): 
     """ 
     Returns a list of tuples. The first element in each 
     tuple is the coded value for the option that will 
     appear in the URL query. The second element is the 
     human-readable name for the option that will appear 
     in the right sidebar. 
     """ 
     if not request.user.is_superuser: 
      return (
       (request.user.customuser.department.name, _(request.user.customuser.department.name)), 
     ) 

    def queryset(self, request, queryset): 
     """ 
     Returns the filtered queryset based on the value 
     provided in the query string and retrievable via 
     `self.value()`. 
     """ 
     # to decide how to filter the queryset. 
     if request.user.is_superuser: 
      if self.value() == request.user.customuser.department.name: 
       return queryset.filter(
        department__in=Department.objects.filter(
         name=request.user.customuser.department.name)) 
     else: 
      return queryset 

在的ModelAdmin :

class CategoryAdmin(admin.ModelAdmin): 

    def changelist_view(self, request, extra_context=None): 
     extra_context = extra_context or {}   

     if request.user.is_superuser: 
      self.list_filter = ['department','name'] 
     else: 
      self.list_filter = (UserCategoryListFilter,) 
+0

對於後代,你能否包括你認爲對你的答案有用的鏈接的相關部分?這樣,如果鏈接發生故障,更改等,您的答案將不會變得無用。非常感謝。 –