Django管理员默认过滤器

时间:2010-06-18 13:08:19

标签: django django-admin

我知道我已经设法做到这一点,但不记得我怎么也找不到任何关于此的文件..

如何在管理员的对象列表视图中默认应用过滤器?

我有一个应用程序列出引号,这些引号具有状态(例如:已接受,被拒绝,暂停......)。

我希望过滤器设置为status ='accepted'默认为..

9 个答案:

答案 0 :(得分:20)

更可重复使用的方法:

class DefaultFilterMixIn(admin.ModelAdmin):
    def changelist_view(self, request, *args, **kwargs):
        from django.http import HttpResponseRedirect
        if self.default_filters:
            try:
                test = request.META['HTTP_REFERER'].split(request.META['PATH_INFO'])
                if test and test[-1] and not test[-1].startswith('?'):
                    url = reverse('admin:%s_%s_changelist' % (self.opts.app_label, self.opts.module_name))
                    filters = []
                    for filter in self.default_filters:
                        key = filter.split('=')[0]
                        if not request.GET.has_key(key):
                            filters.append(filter)
                    if filters:                        
                        return HttpResponseRedirect("%s?%s" % (url, "&".join(filters)))
            except: pass
        return super(DefaultFilterMixIn, self).changelist_view(request, *args, **kwargs)            

然后在ModelAdmin上定义default_filters:

class YourModelAdmin(DefaultFilterMixIn):
    ....
    default_filters = ('snapshot__exact=0',)

答案 1 :(得分:7)

最后,这就是我想要的:

def changelist_view(self, request, extra_context=None):
    if not request.GET.has_key('status__exact'):
        q = request.GET.copy()
        q['status__exact'] = '1'
        request.GET = q
        request.META['QUERY_STRING'] = request.GET.urlencode()
    return super(SoumissionAdmin,self).changelist_view(request, extra_context=extra_context)

另一方面,使用admin类中的queryset方法不起作用。实际上它会对结果进行过滤,但会使过滤器功能失效。

我发现的解决方案也不完美,用它来选择“全部/过滤器”是不可能的。在我的情况下,它不是戏剧性的,虽然它会很好......

答案 2 :(得分:6)

您可以覆盖查询集

class QuoteAdmin(admin.ModelAdmin):
    def get_queryset(self, request):
        return super(QuoteAdmin,self).get_queryset(request).filter(status="accepted")

但是,通过覆盖查询集,您将无法查看没有“已接受”状态的引号。

或者,您可以链接到以下URL,将过滤器添加到GET参数。

/admin/myapp/quote/?status=accepted

答案 3 :(得分:5)

我通过支持'all'解决了这个问题。

在models.py中:

STATUSES_CHOICE = (
    ('0', 'Active'),
    ('1', 'Deactive'),
    ('2', 'Suspended'),
)

class Client(models.Model):
    ...
    status = models.IntegerField(verbose_name=_('Status'),
                                 default=0,
                                 db_index=True)

在admin.py中:

class StatusAdminFilter(SimpleListFilter):
    title = _('Status')
    parameter_name = 'status'
    all_param_value = 'all'

    def lookups(self, request, model_admin):
        return STATUSES_CHOICE

    def queryset(self, request, queryset):
        status = self.value()
        try:
            return (queryset if status == self.all_param_value else
                    queryset.filter(status=int(status)))
        except ValueError:
            raise Http404

    def choices(self, cl):
        yield {'selected': self.value() == self.all_param_value,
               'query_string': cl.get_query_string(
                   {self.parameter_name: self.all_param_value}, 
                   [self.parameter_name]),
               'display': _('All')}
        for lookup, title in self.lookup_choices:
            yield {'selected': self.value() == lookup,
                   'query_string': cl.get_query_string(
                       {self.parameter_name: lookup}, []),
                   'display': title}


class ClientAdmin(admin.ModelAdmin):
    list_filter = (StatusAdminFilter,)

    def changelist_view(self, request, extra_context=None):
        if not request.GET.has_key('status'):
            q = request.GET.copy()
            q['status'] = '0'  # default value for status
            request.GET = q
            request.META['QUERY_STRING'] = request.GET.urlencode()
        return super(ClientAdmin, self).changelist_view(
            request, extra_context=extra_context)

答案 4 :(得分:5)

简洁干净的解决方案。单击更改列表视图时,可以使用“全部”选项。

    def changelist_view(self, request, extra_context=None):
        if not request.META['QUERY_STRING'] and \
            not request.META.get('HTTP_REFERER', '').startswith(request.build_absolute_uri()):
            return HttpResponseRedirect(request.path + "?status__exact=1")
        return super(YourModelAdmin,self).changelist_view(request, extra_context=extra_context)

答案 5 :(得分:2)

我想我已经找到了一种方法来做到这一点而不限制用户。只需查看引用来确定用户是否刚到达此页面。如果是这样,则根据该过滤器将它们重定向到您想要的默认网址。

def changelist_view(self, request, extra_context=None):
    try:
        test = request.META['HTTP_REFERER'].split(request.META['PATH_INFO'])
        if test and test[-1] and not test[-1].startswith('?') and not request.GET.has_key('status__exact'):
            return HttpResponseRedirect("/admin/app/model/?status__exact=1")
    except: pass # In case there is no referer
    return super(MyModelAdmin,self).changelist_view(request, extra_context=extra_context)

答案 6 :(得分:1)

这对我有用,并避免使用" All" h3提到的问题。

class MyAdmin(admin.ModelAdmin):
  def changelist_view(self, request, extra_context=None):
    referer = request.META.get('HTTP_REFERER', '')
    showall = request.META['PATH_INFO'] in referer and not request.GET.has_key('timeframe')
    if not showall and not request.GET.has_key('param_name_here'):
        q = request.GET.copy()
        q['param_name_here'] = 'default_value_here'
        request.GET = q
        request.META['QUERY_STRING'] = request.GET.urlencode()
    return super(SerializableAdmin,self).changelist_view(request, extra_context=extra_context)

答案 7 :(得分:1)

这是我对glic3rinu代码的更新(请参阅那里的评论),它适用于Python 3.4和Django 1.9.7:

class DefaultFilterMixIn(admin.ModelAdmin):
    def changelist_view(self, request, *args, **kwargs):
        from django.http import HttpResponseRedirect
        if self.default_filters:
            #try:
                test = request.META['HTTP_REFERER'].split(request.META['PATH_INFO'])
                if test and test[-1] and not test[-1].startswith('?'):
                    url = reverse('admin:{}_{}_changelist'.format(self.opts.app_label, self.opts.model_name))
                    filters = []
                    for filter in self.default_filters:
                        key = filter.split('=')[0]
                        if not key in request.GET:
                            filters.append(filter)
                    if filters:                     
                        return HttpResponseRedirect("{}?{}".format(url, "&".join(filters)))
            #except: pass
        return super(DefaultFilterMixIn, self).changelist_view(request, *args, **kwargs)            

答案 8 :(得分:0)

这是我尝试在admin中设置默认过滤器(仅使用Django 1.11测试):

in-line

诀窍是检查class ZeroCountListFilter(admin.SimpleListFilter): title = _('include zero count') parameter_name = 'count' def choices(self, changelist): yield { 'selected': self.value() is None or self.value() == 0, 'query_string': changelist.get_query_string({}, [self.parameter_name]), 'display': _('No'), } yield { 'selected': self.value() == '1', 'query_string': changelist.get_query_string({self.parameter_name: '1'}, []), 'display': _("Yes"), } def lookups(self, request, model_admin): return ( ('0', _('No')), ('1', _('Yes')), ) def queryset(self, request, queryset): if self.value() is None or self.value() == '0': return queryset.exclude(count=0) else: return queryset 以获取默认行为