Django Admin:需要有条件地显示字段
根据其他字段的值有条件地在管理中显示字段的最佳方法是什么?
我特别考虑的是 add_form 和 change_form。每当选择某个选项时,我想隐藏或禁用某些字段。
我认为这可能需要一个 javascript 解决方案,但我想知道是否有更好的(即内置的)方法来做到这一点。
What is the best way to conditionally display a field in the admin depending upon the values of other fields?
In particular I'm thinking about the add_form and change_form. Whenever a certain choice is selected I'd like to hide or disable some fields.
I'm thinking that this might require a javascript solution, but am wondering if there is a better (i.e. builtin) way to do this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
伯恩哈德是对的。您也许可以破解管理视图和模板,以有条件地显示/不显示字段的小部件,但如果您想根据管理中的用户行为动态地执行此操作,则将使用 javascript。
不过,这并没有那么可怕。至少 Django 管理模板具有特定于模型和实例的 id,可以让您对显示/隐藏行为进行精细控制。
Bernhard is right. You might be able to hack the admin view and template to conditionally show/not show widgets for a field, but if you want to do it dynamically based on user behaviors in the admin, you'll be using javascript.
It's not so terrible, though. At least the Django admin templates have model- and instance-specific ids to give you granular control over your show/hide behavior.
我的回答可能听起来很深奥 - 但我怀疑您可能采取的设计方向可能会从一些重新考虑中受益。当一个界面需要太多的 TLC 来诉诸 AJAX 来实现卓越的用户体验时,我倾向于不使用管理界面。
我个人对 Django 管理界面的看法是,它是一个很棒的免费赠品,它为我提供了基本级别的即时 CRUD 视图。我不会为那些需要更用户友好界面的人提供支持(即使其中一些用户正在处理管理功能)。在尝试使用管理界面执行这些类型的 Ajax UI/UX 和复杂表单验证时,您将获得技术债务。
My answer may sound esoteric - but I suspect the design direction you may be taking could benefit from some reconsideration. When an interface requires that much TLC to resort to AJAX to make for a superior UX I am inclined to not use Admin interface for that.
My personal view of the Admin interface of Django is that it is a great freebie that gives me an instant CRUD view at a basic level. I would refrain from piggy backing on it for those who need a more user friendly interface (even if some of these users are handling admin functions). You will acquire technical debt in trying to do these type of Ajax UI/UX and complex form validations using the Admin interface.
我认为您应该能够创建自己的 ModelForm 并指定管理员使用它(https://docs.djangoproject.com/en/1.7/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form)。
使用表单的 _init__() 方法有选择地显示字段。
我会尝试一下,如果有效的话更新这个答案。
(实际上重新阅读问题,这取决于。如果在加载页面之前设置“其他字段的值”,这个想法应该可行。如果您想要即时响应 - 单击一个字段,另一个字段出现/消失,是的,您会需要 JavaScript)。
I think you should be able to create your own ModelForm and specify that the admin uses that (https://docs.djangoproject.com/en/1.7/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form).
Use the _init__() method of the form to selectively display the fields.
I will give it a try and update this answer if it works.
(Actually re-reading the question, it depends. If "values of other fields" is set before the page is loaded, this idea should work. If you want an instant response - click one field and another appears/disappears, yes you will need JavaScript).