如何在 Django Admin 中仅折叠一个字段?
问题描述
django 管理员允许您指定字段集.您正确地构建了一个将不同字段组合在一起的元组.您还可以为某些字段组指定类.其中一个类是折叠,它将将该字段隐藏在可折叠区域下.这有利于隐藏很少使用或高级的字段以保持 UI 整洁.
The django admin allows you to specify fieldsets. You properly structure a tuple that groups different fields together. You can also specify classes for certain groups of fields. One of those classes is collapse, which will hide the field under a collapsable area. This is good for hiding rarely used or advanced fields to keep the UI clean.
但是,我有一种情况,我想在许多不同的应用程序上隐藏一个单独的字段.为了在每个 admin.py 文件中创建一个完整的字段集规范,只需将一个字段放入折叠区域,这将需要大量输入.这也造成了维护困难的情况,因为我每次编辑关联模型时都必须编辑字段集.
However, I have a situation where I want to hide just one lonesome field on many different apps. This will be a lot of typing to create a full fieldset specification in every admin.py file just to put one field into the collapsed area. It also creates a difficult maintenance situation because I will have to edit the fieldset every time I edit the associated model.
我可以使用 排除选项.我想要类似的崩溃.这可能吗?
I can easily exclude the field entirely using the exclude option. I want something similar for collapse. Is this possible?
解决方案
我知道 Django 没有内置的方法来做这件事,但我可以想到几种方法,你可以一次性做某事,而不必手动修改大量的字段集.
Django doesn't have a built in way of doing this that I'm aware of but I can think of a couple of ways you could do something once, rather than having to manually modify lots of fieldsets.
一种方法是使用 javascript 重写页面标记.也许 javascript 可以有一个字段名列表,当它找到其中一个时,它会隐藏该字段和它的标签,并向页面添加一个按钮来切换这些不可见的字段.
One approach would be to use javascript to rewrite the page markup. Maybe the javascript could have a list of fieldnames and whenever it finds one of those it hides the field and it's label and adds a button to the page to toggle these invisible fields.
另一种方法只涉及 python.通常,您只需将管理中的字段集属性指定为元组.但是您可以将其指定为一个导入函数,该函数将通常的元组作为参数.在您的设置文件中,您可以指定要隐藏的字段名列表.然后,您需要编写一个返回修改后的元组的函数,将任何与您的字段名匹配的字段与折叠类一起移动到一个新的字段集中.
The other approach would just involve python. Normally you just specify the fieldsets attribute in the admin as a tuple. But you could specify it as an imported function which takes the usual tuple as an argument. In your settings file you could specify a list of fieldnames you want to hide. You then need to write a function that returns a modified tuple, moving any fields that match one of your fieldnames into a new fieldset along with the collapse class.
例如,在您的管理类中,您可以执行类似的操作(您需要编写和导入 hide_fields).
For example in your admin class you could do something like this (you need to write and import hide_fields).
fieldsets = hide_fields(
(None,
{'fields':('title', 'content')}
)
)
这可能最终被解释为以下内容,假设设置文件中的内容是您想要隐藏的内容:
This might end up being interpreted as the following, assuming content is in the settings file as something you want to hide:
fieldsets = (
(None,
{'fields':('title',)}
),
('Extra',
{
'fields': ('content',),
'classes':('collapse',),
}
),
)
相关文章