How can I access The request.data Inside My post_save signal after creating the Model Objects

59 Views Asked by At

I want to create Projects with Documents

But It took time So i wanna add document after creating the projects

But I am giving Documents related details inside my request body

# Define the signal receiver function
@receiver(post_save, sender=Project)
def attach_documents_to_project(sender, instance, created, **kwargs):
    if created:
        attachments_data = instance.request.data.get('document')
2

There are 2 best solutions below

0
willeM_ Van Onsem On

You don't. signals, just like models are request unaware. This is a core design feature of most model-view-viewmodel (MVVM) architectures. In fact it is not even said that there is a request involved. You could also create or update or remove records with a management command [Django-doc].

These are all reasons not to use signals [django-antipatterns] in the first place. If something is request-oriented, it belongs in a view, not in the model layer, where signals essentially reside. You can define a helper function that you then invoke in view(s) where you want to trigger this logic.


disclosure: I am the author if that article.

2
G Haridev On

You can set a _request attribute for the instance before calling the save method and access that attribute inside the receiver method.

Inside views.py/serializers.py:

instance._request = request
instance.save()

Inside receiver method:

@receiver(post_save, sender=Project)
def attach_documents_to_project(sender, instance, created, **kwargs):
    if created:
        try:
            attachments_data = instance._request.data.get('document')
        except AttributeError:
            pass

Make sure to wrap the statement between try/except or put it under if hasattr(instance, "_request"):.