Default django-admin list filter

2019-08-10 22:21发布

My question is just an extension of this thread [Question]http://stackoverflow.com/questions/851636/default-filter-in-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  . 

What I want is if the superuser is logged in ,the filter should show all four criteria All,A,B,C and if the user is other than superuser filter should only show All, A, B.

How can i acheive this ? Here is my actual piece of 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 

1条回答
▲ chillily
2楼-- · 2019-08-10 22:56

I think the new FilterSpec API in Django 1.4 gives you exactly what you need here. Check out the docs on list_filter. In 1.4 you can now make custom list filters that subclass django.contrib.admin.SimpleListFilter and give you the power to write custom lookup and queryset code, and since the request is passed in you can do a simple conditional with is_superuser.

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

read the example code in the docs carefully and I think it will all be clear.

查看更多
登录 后发表回答