如何在django post_save监听器中获取请求对象

How to get the request object in django post_save listener

@receiver(post_save, sender=StudentActionModel)
def save_student_activity(sender, instance, **kwargs):

    # update the model object with some info from the request object
    instance.came_from = request.REQUEST.get('request_came_from')
    instance.save()

用户故事: 一个用户点击某处,我们正在记录他的动作。我们能否以某种方式访问​​原始请求对象,以便我们能够从中提取一些所需信息?

问题:我们不能更改 StudentActionModel 代码,我们正在为原始 Django 应用程序编写插件,不能更改任何原始代码。我们只是为 'post_save' 信号定义一个侦听器,我们需要来自原始请求对象的一段数据。

您不能假设只有视图代码会调用 StudentActionModel.save() - 它可以由管理命令或任何脚本调用 - 这就是为什么 Model.save() norpost_save()nor any of thedjango.db` 信号得到请求。长话短说:您必须在视图(或自定义中间件)中处理此问题,而不是在 orm 级别。