我知道我以前已经成功做到了这一点,但是我不记得如何操作,也找不到任何相关文档...
在管理员页面中,如何默认应用一个对象列表的筛选器?
我有一个应用程序,它列出报价单,这些报价单有一个状态(例如:已接受、已拒绝、挂起等)。
我想默认设置筛选器为status='accepted'。
我知道我以前已经成功做到了这一点,但是我不记得如何操作,也找不到任何相关文档...
在管理员页面中,如何默认应用一个对象列表的筛选器?
我有一个应用程序,它列出报价单,这些报价单有一个状态(例如:已接受、已拒绝、挂起等)。
我想默认设置筛选器为status='accepted'。
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',)
snapshot=0
而不是snapshot__exact=0
时才有效。另外,由于javascript出现问题(控制台显示:“Uncaught TypeError: Object [object Object] has no method 'actions'”),过滤器不再起作用,这可能是由于grappelli引起的。抱歉这是一个长句子,哈哈。 - Dan Mantylarequest.GET.has_key(key)
”已被替换为“key in request.GET
”。(更新的代码太长无法在此处接受) - Jens-Erik Weber最终,这就是我一直在寻找的:
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)
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
我使用支持“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)
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)
我认为我找到了一种不限制用户的方法来实现这个问题。只需查看引荐者以确定用户是否刚刚到达此页面。如果是,根据该过滤器将其重定向到您想要的默认URL。
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)
这是我对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)
这对我有用,并避免了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)
这是我尝试在管理员中设置默认过滤器的方法(仅在Django 1.11中进行了测试):
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
诀窍在于检查self.value() is None
以获取默认行为