为模型更改表单视图设置自定义工作流程

Setting up a custom workflow for the model change-form view

上下文

我有一个模型,我们称它为Application

class Application(models.Model):
    # various fields here

    status = status = models.CharField(
        max_length=100,
        choices=APPLICATION_STATUSES,
        default=PENDING_STATUS[0],
    )

    assigned_operator = models.OneToOneField(
        settings.AUTH_USER_MODEL,
        on_delete=models.PROTECT,
        editable=True,
        null=True,
    )

这个模型有一些字段,但我们在这里关心的是 status,它只是一个选择字段,以及 assigned_operator 字段,它定义了一个 1-1 关系User 实例。该模型还定义了相应的 ApplicationAdmin 视图。

描述

要求 是,在尝试编辑应用程序时,从管理员视图,默认工作流程,您可以在其中进行所需的任何更改,然后只需保存表单,应该替换为以下工作流程:

问题

好吧,问题是我对 django 还很陌生,我在这里很迷茫。

我知道的:

{%  extends 'admin/change_form.html' %}

{% block submit_buttons_bottom %}
  <div>
    <input type="submit" value="Assign to me" class="default" name="????">
  </div>
{% endblock %}

我不知道的事

虽然欢迎代码示例,但我不要求您给我实现。清除 directives/instructions 就可以了,我只需要一些指导

谢谢

更新 我想出了如何通过使用 ModelAdminchange_view 方法将信息传递给模板。所以现在我可以有条件地显示适当的按钮了。

更新 2 刚刚弄清楚如何在单击按钮后对模型执行某些操作。我们可以为此使用 response_changechange_view(不确定哪个选项更“正确”,但两者都有效。不同之处在于 change_view 在视图渲染之前运行,而 response_change 在保存表单并更新模型后运行)

How to conditionally show either the "Assign to myself" or the group-of-3-buttons, depending on the assigned_operator value of the Application model.

通过在我们的自定义管理视图中覆盖 ModelAdminchange_view 方法,我们可以将额外的上下文传递给我们的 html 模板,如文档 here 中所示.所以现在我们可以通过在模板中添加 {% if context_value %} 来有条件地显示适当的按钮。

How to connect those new custom buttons to interact with the models and do stuff on them, when they are clicked

我们可以在管理员视图中使用 response_changechange_view。在那里,我们可以在 request.POST 值(例如 _save 等)中监听按钮名称的值,并据此采取行动

(不确定哪个是更“正确”的选项,response_changechange_view 但两者都有效。不同之处在于 change_view 在视图之前运行甚至渲染,而 response_change 在表单保存和模型更新后运行)

In general how the change_form.html part, which is just a template as far as I know, can know things from the currently displayed model instance and the current user.

从管理视图传递上下文和从 request.POST

中的模板监听按钮名称的组合