在 Django Admin 中为 list_filter 创建自定义过滤器

2024-01-24

我想为 django admin 制作自定义过滤器,而不是普通的“is_staff”和“is_superuser”。我读过这个列表过滤器 https://docs.djangoproject.com/en/dev/ref/contrib/admin/在 Django 文档中。 自定义过滤器的工作方式如下:

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 制作了自定义函数,如下所示:

def Student_Country(self, obj):
    return '%s' % obj.country
Student_Country.short_description = 'Student-Country'

我是否可以在 list_filter 中使用 list_display 的自定义函数,而不是为 list_filter 编写新的自定义函数?欢迎任何建议或改进。需要一些指导...谢谢...


您确实可以通过扩展 SimpleListFilter 将自定义过滤器添加到管理过滤器。例如,如果您想将“非洲”的大陆过滤器添加到上面使用的国家/地区管理过滤器中,您可以执行以下操作:

在admin.py中:

from django.contrib.admin import SimpleListFilter

class CountryFilter(SimpleListFilter):
    title = 'country' # or use _('country') for translated title
    parameter_name = 'country'

    def lookups(self, request, model_admin):
        countries = set([c.country for c in model_admin.model.objects.all()])
        return [(c.id, c.name) for c in countries] + [
          ('AFRICA', 'AFRICA - ALL')]

    def queryset(self, request, queryset):
        if self.value() == 'AFRICA':
            return queryset.filter(country__continent='Africa')
        if self.value():
            return queryset.filter(country__id__exact=self.value())

class CityAdmin(ModelAdmin):
    list_filter = (CountryFilter,)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Django Admin 中为 list_filter 创建自定义过滤器 的相关文章

随机推荐

  • VS Code 错误:(this.configurationService.getValue(...) || []).filter 不是函数

    我刚刚开始在 VS Code 中收到此错误 它阻止我创建新文件 甚至无法打开文件 VS Code 显示的弹出错误是 this configurationService getValue filter is not a function 这个
  • 为什么不起作用

    我希望在名字和姓氏之间添加空格 但是当我运行代码时它不会增加空间 我也尝试添加选项卡空间 但它渲染不正确 字符集设置为utf 8 如所附的html所示 export class AppComponent implements OnInit
  • 在 PHP 中读取 COM(串行调制解调器)

    在 PHP 中读取 COM 串行调制解调器 我需要一个 COM 接口 Windows COM2 来使用 PHP 进行读取 这个演示正在进行中 读取有问题 有时会运行 也许还有另一种方法 没有dio ni C w32api register
  • htaccess 相同的文件夹和文件名

    如何设置 htaccess 来区分文件和同名文件夹 我的网站下有 index php team php team Justin php team martin php 和一个带有 URL 重写的 htaccess 以制作漂亮的 url 并删
  • 使用mockito或Jmockit模拟私有静态最终字段

    我在用私有静态最终记录器我班上的领域 我想要LOGGER isInfoEnabled 返回方法false 如何使用mockito或jMockit模拟静态最终字段 我的班级是 import org slf4j Logger import or
  • MS SQL Server 中的自定义聚合函数?

    如何在 MS SQL Server 中创建自定义聚合函数 举个例子会有很大帮助 SQL Server 2000 并不正式支持自定义聚合函数 然而 我最近也需要该功能 我发现这篇文章很有启发性 http weblogs sqlteam com
  • Scipy 负距离?什么?

    我有一个输入文件 其中包含小数点后 4 位的浮点数 i e 13359 0 0000 0 0000 0 0001 0 0001 0 0002 0 0003 0 0007 第一个是 id 我的班级使用loadVectorsFromFile方法
  • 隐藏移动设备的滚动条,同时保持滚动能力

    我的问题几乎与此相同 隐藏滚动条 但保持滚动的原生感觉 https stackoverflow com questions 6635513 hide the scrollbar but keep the ability to scroll
  • 错误 1 ​​找不到类型或命名空间名称“控制器”(是否缺少 using 指令或程序集引用?)

    当我尝试在 asp net mvc3 中构建项目时 出现27个错误 说mvc相关的类不存在 下面是一个例子 Error 1 The type or namespace name Controller could not be found a
  • 通过虚拟线程中的调用在主线程中执行Python函数

    我有一个 Python 脚本 用于处理来自 NET Remoting 的异步回调 这些回调在虚拟 工作 线程中执行 从我的回调处理程序内部 我需要调用我在脚本中定义的函数 但我需要该函数在主线程中执行 主线程是向服务器发送命令的远程客户端
  • 使用Java创建视频播放器

    我需要为我的项目使用 Java 创建一个视频播放器 我已经在网上查过很多例子了 其中一些运行 但不显示任何屏幕 我只能听到视频的声音 请帮我解决这个问题 我正在使用下面的导入 import javax media 编辑 下面是我使用的代码
  • 背景图像 url() 在实时服务器上有效,但当我在浏览器中打开 index.html 时却不起作用?

    由于其他属性适用 因此正确选择了该元素 没有控制台错误 我努力了 img 英雄 jpg 当我点击 VS Code 中的链接时有效 img 英雄 jpg 当我点击时起作用 英雄 jpg 当我点击时工作 img 英雄 jpg 不起作用 完整路径
  • 将动态 Web 项目导入 Eclipse

    我一直在 Eclipse 中开发一个动态 Web 项目 我最近重新安装了我的操作系统 并且使用了干净的 Eclipse 我可以导入我的网络项目 但是当我尝试吃午饭 在服务器上运行 时 我总是收到此消息 The selection canno
  • 倾斜的div边框透明度

    所以 我知道如何使用 after 和边框为现代布局制作倾斜的 div 但是 我想知道您是否可以使用它通过透明度裁剪掉 div 的一部分 例如 假设我有一排带有背景图像的卡片 我想要在这些卡片上产生倾斜效果 但是 这里的倾斜只是页面 不是卡片
  • /rest-auth/password/reset/ 处的 NoReverseMatch

    我有一个带有角度前端的 Django 应用程序 当我尝试从前端发送密码重置请求时 出现以下错误 使用参数 和关键字反转 password reset confirm 参数 u uidb64 MTE u token u 3z4 eadc7ab
  • HTTP 网站上出现“阻止加载混合活动内容”

    Problem 我正在开发一个使用 HTTP 协议提供服务的网站 在开发中 我使用 Webpack 及其 webpack dev server 它在本地提供页面服务http localhost 9090 我很惊讶地在 Firefox 58
  • 如何创建唯一 ID,例如 YouTube?

    我一直想知道他们是如何以及为什么这样做 一个例子 http youtube com watch v DnAMjq0haic http youtube com watch v DnAMjq0haic 这些 ID 是如何生成的 并且不会重复 这
  • ASP.NET Identity 出现“创建模型时无法使用上下文”异常

    为什么当我们调用 AccountApiController Register 方法时会发生这种情况 什么试图使用上下文 什么试图创建上下文 我们如何避免这种情况 我们如何调试这个 Message 发生错误 ExceptionMessage
  • 覆盖命名空间中导入的函数

    As the termplotR 中的函数包含一些奇怪的代码 这些代码给我带来了烦人的错误 我想在我自己的测试代码中覆盖它 直到找到更永久的解决方案 问题是更改的函数没有被加载mgcv包裹 这mgcv包从其命名空间中的 stats 包加载
  • 在 Django Admin 中为 list_filter 创建自定义过滤器

    我想为 django admin 制作自定义过滤器 而不是普通的 is staff 和 is superuser 我读过这个列表过滤器 https docs djangoproject com en dev ref contrib admi