2012-05-02 59 views
1

我的问题只是这个线程的扩展[问题] http://stackoverflow.com/questions/851636/default-filter-in-django-admin。默认django-admin列表筛选器

from myproject.myapp.mymodels import fieldC 


class Poll(models.Model): 

    fieldA = models.CharField(max_length=80, choices=CHOICES.MyCHOICES) 
    fieldB = models.ForeignKey(fieldC) 

admin.py 

list_display = ('fieldB__fieldc1') 

Now my list filter shows four criteria All, A ,B ,C . 

我要的是,如果超级用户登录,过滤器应显示所有四个标准全部,A,B,C,如果用户是比超级过滤器等应仅显示所有,A,B。

我该如何实现这个目标? 这里是我的实际件admin.py

def changelist_view(self, request, extra_context=None): 

     referer = request.META.get('HTTP_REFERER', '') 
     test = referer.split(request.META['PATH_INFO']) 
     if test[-1] and not test[-1].startswith('?'): 
      if not request.GET.has_key('patient__patient_type__exact'): 

       q = request.GET.copy() 
       q['patient__patient_type__exact'] = 'Real' 
       request.GET = q 
       request.META['QUERY_STRING'] = request.GET.urlencode() 
       if not request.user.is_superuser: 
        q['patient__patient_type__exact'] = 'Real' 
    return super(VisitAdmin, self).changelist_view(request, extra_context) 


Thanks in advance 
+0

我很困惑你是否试图为用户和su创建*不同的默认过滤器*,或者为用户和su创建不同的过滤器查询集? –

+0

我对超级用户和其他用户都使用相同的过滤器。我只是想在超级用户登录时看到他应该看到list_filter中的所有选项,如“真实”,“测试”和“访客”,他应该能够过滤该表的行,但如果用户不是超级用户,过滤器应该只在list_filter中显示“Real”和“Guest”选项,他应该只能过滤“Real”和“Guest”选项的行。 –

回答

0

我想在Django 1.4新FILTERSPEC API给你的,你在这里需要什么。 list_filter上的Check out the docs。在1.4中,您现在可以创建自定义列表筛选器,子类为django.contrib.admin.SimpleListFilter,并为您提供编写自定义查询和查询集代码的功能,并且由于请求已传入,因此您可以使用is_superuser执行简单条件。

if request.user.is_superuser: 
    # pass one set of lookups 
else: 
    # pass a different set 

仔细阅读文档中的示例代码,我认为这一切都很清楚。