在Django Admin中创建list_filter的自定义过滤器 [英] Creating Custom Filters for list_filter in Django Admin
问题描述
我想为django管理员定制过滤器,而不是正常的is_staff和is_superuser。我已经在Django文档中阅读过 list_filter 。
自定义过滤器以这种方式工作:
I would like to make custom filters for django admin instead of the normal 'is_staff' and 'is_superuser'. I have read this list_filter in Django docs. Custom Filters work in this way:
from datetime import date
from django.utils.translation import ugettext_lazy as _
from django.contrib.admin import SimpleListFilter
class DecadeBornListFilter(SimpleListFilter):
# Human-readable title which will be displayed in the
# right admin sidebar just above the filter options.
title = _('decade born')
# Parameter for the filter that will be used in the URL query.
parameter_name = 'decade'
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.
"""
return (
('80s', _('in the eighties')),
('90s', _('in the nineties')),
)
def queryset(self, request, queryset):
"""
Returns the filtered queryset based on the value
provided in the query string and retrievable via
`self.value()`.
"""
# Compare the requested value (either '80s' or '90s')
# to decide how to filter the queryset.
if self.value() == '80s':
return queryset.filter(birthday__gte=date(1980, 1, 1),
birthday__lte=date(1989, 12, 31))
if self.value() == '90s':
return queryset.filter(birthday__gte=date(1990, 1, 1),
birthday__lte=date(1999, 12, 31))
class PersonAdmin(ModelAdmin):
list_filter = (DecadeBornListFilter,)
但是我已经为list_display定制了这样的功能:
But i have already made custom functions for list_display like this:
def Student_Country(self, obj):
return '%s' % obj.country
Student_Country.short_description = 'Student-Country'
我可以使用list_filter中的list_display的自定义函数,而不是为list_filter编写新的自定义函数?任何建议或改进是受欢迎的..需要一些指导这个...谢谢...
Is it possible i could use the custom functions for list_display in list_filter instead of writing a new custom function for list_filter? Any suggestions or improvements are welcome.. Need some guidance on this... Thanks...
推荐答案
这是你想要的。检查以下链接
https://djangosnippets.org/snippets/2885/
Is this you want. Check the below link https://djangosnippets.org/snippets/2885/
这篇关于在Django Admin中创建list_filter的自定义过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!