如何在django post_save监听器中获取请求对象 [英] How to get the request object in django post_save listener

查看:409
本文介绍了如何在django post_save监听器中获取请求对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $

$ b $更新模型对象来自请求对象的一些信息
instance.came_from = request.REQUEST.get('request_came_from')
instance.save()

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



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

解决方案

你不能假设只有查看代码将调用 StudentActionModel.save() - 它可以被管理命令或任何脚本调用 - 这就是为什么 Model.save()或 post_save()也不会有任何 django.db`信号获取请求。要做一个很长的故事:你必须在视图(或定制中间件)中处理这个问题,而不是在orm级别。


@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()

The user story: An user clicks somewhere, and we are recording his action. Can we, somehow, get access to the original request object so we will be able to extract some required information from it?

The catch: We cannot change the StudentActionModel code, we're writing a plugin to the original Django application and can't change any of the original code. We are just defining a listener for the 'post_save' signal and we need a piece of data from the original request object.

解决方案

You cannot assume that only view code will call StudentActionModel.save() - it could be called by a management command or just any script - which is why neither Model.save() norpost_save()nor any of thedjango.db` signals get the request. To make a long story short: you'll have to handle this in the views (or in a custom middleware), not at the orm level.

这篇关于如何在django post_save监听器中获取请求对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆