@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”信号定义一个监听器,我们需要来自原始请求对象的一段数据。
请您参考如下方法:
您不能假设只有 View 代码会调用 StudentActionModel.save() - 它可以由管理命令或任何脚本调用 - 这就是为什么 Model.save() post_save()或任何django.db` 信号都无法获得请求。长话短说:您必须在 View (或自定义中间件)中处理此问题,而不是在 orm 级别。
