How to get the request object in django post_save listener

泄露秘密 提交于 2019-12-22 01:30:07

问题


@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.


回答1:


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.



来源:https://stackoverflow.com/questions/31429038/how-to-get-the-request-object-in-django-post-save-listener

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!