Kiril Kirilov
Kiril Kirilov

Reputation: 11257

How to get the request object in django post_save listener

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

Upvotes: 1

Views: 3108

Answers (1)

bruno desthuilliers
bruno desthuilliers

Reputation: 77912

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.

Upvotes: 5

Related Questions