fic*_*ion 1 python django django-signals
@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()
Run Code Online (Sandbox Code Playgroud)
用户故事:用户单击某处,我们正在记录他的行为。我们可以以某种方式获得对原始请求对象的访问权限,以便我们能够从中提取一些必需的信息吗?
要注意的是:我们无法更改StudentActionModel代码,我们正在为原始Django应用程序编写插件,并且无法更改任何原始代码。我们只是为“ post_save”信号定义一个监听器,我们需要来自原始请求对象的数据。
您不能假定仅视图代码将被调用StudentActionModel.save()-它可以由管理命令或任何脚本来调用-这就是为什么Model.save() norpost_save()nor any of thedjango.db`信号均未获取请求的原因。长话短说:您必须在视图(或自定义中间件)中而不是在orm级别处理此问题。