简体   繁体   English

Django admin中的复选框在没有BooleanField的情况下在保存时运行Python函数

[英]Check box in Django admin run a Python function on save without a BooleanField

Is there a way to have a check box appear in Django admin, but instead of associating it with a BooleanField, having it run a function if it is / is not checked upon save? 有没有一种方法可以在Django admin中显示一个复选框,而不是将其与BooleanField关联,而是在保存时未选中/的情况下让它运行一个函数? I don't need to store a Boolean in the database, but may need to store something depending on other fields, and whether the check box was checked. 我不需要在数据库中存储布尔值,但是可能需要存储一些东西,具体取决于其他字段以及是否已选中复选框。

In particular, I would like to store a ForeignKey if the check box was just checked, empty it (set ForeignKey to null) if the check box was just unchecked, and do nothing it the check box state stayed the same. 特别是,如果要将复选框选中,我想存储一个ForeignKey,如果只是取消选中该复选框,则将其清空(将ForeignKey设置为null),并且不做任何事情,复选框状态保持不变。 I don't want to display what this ForeignKey is to the user, just set it or delete it behind the scenes. 我不想向用户显示此ForeignKey是什么,只需对其进行设置或在后台将其删除。

You can add any arbitrary fields to a form: they need to be form fields (eg forms.BooleanField) but as long as they don't also exist on the model they won't be saved. 您可以将任意字段添加到表单:它们必须是表单字段(例如,forms.BooleanField),但是只要它们不存在于模型中,就不会被保存。

You can then take any action you like in the form's clean() method, or in the modeladmin's save_form method. 然后,您可以在表单的clean()方法或modeladmin的save_form方法中执行所需的save_form

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM