0

Problem

Django models send the signal post_save when a model is saved. The post_save, however, does not have access to the request object. I need to access variables like request.user and send it with the signal.

Possible solutions

  • Admin - Override admin save_model to send post_save with some extra parameters from the request object.

  • DRF API - After a model is created or updated, send post_save, again with parameters from the request object.

Question

In both the above cases, model.save() will send the post_save by default. How can I override save to either send a custom signal or resend post_save with request.user. How should this be done?

Ajoy
  • 1,838
  • 3
  • 30
  • 57
  • Are you sure you want a `post_save` signal? If you need to access `request`, you should probably define custom signal and manually call it from the view. – Назар Топольський Nov 07 '16 at 14:12
  • @НазарТопольський I wanted to use `post_save` because it is the default signal. But I am open to any other viable solution. – Ajoy Nov 08 '16 at 08:47

1 Answers1

0

You can access the user object this way on the User model:

from django.contrib.auth.models import User

# post save for creating customer on user saving
def post_save_function(sender, instance, created, **kwargs):

    # create customer instance 
    if created:



post_save.connect(post_save_function, sender=User)

You will have access to the User in the instance variable

aliasav
  • 3,048
  • 4
  • 25
  • 30
  • I guess you did not understand my question. – Ajoy Oct 25 '16 at 15:56
  • All django models emit `post_save` signals. I want to send (resend) these signals, through the DRF API or Django admin, but with an additional `request.user` parameter. – Ajoy Oct 25 '16 at 16:18