问题
@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() nor
post_save()nor any of the
django.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