Calling a function in Django after saving a model
Asked Answered
S

2

16

Context: I'm making a blog. This blog stores information on articles in a database via a Django model. I have a FileField in said model that takes an archive of all the assets that go with this file. I add articles through the admin site.

I want to call a function that unpacks this file immediately after the the object is saved to the model. Where would I write this function?

Sites answered 31/3, 2017 at 16:40 Comment(2)
could you add the code where you are saving this object?Maurey
That's the problem. I'm saving these objects through the admin site, so I don't know where the code is or what it looks like. If I could figure out where and how it's being saved, I can alter it to call my function right afterwards.Sites
K
27

You can use signal dispatcher included in Django.

from django.db.models.signals import post_save
from django.dispatch import receiver

from myapp.models import Blog

@receiver(post_save, sender=Blog)
def my_handler(sender, **kwargs):
    print('post save callback')

See https://docs.djangoproject.com/en/stable/ref/signals/#post-save for more information.

Kratz answered 31/3, 2017 at 17:57 Comment(0)
S
3

Maybe you can use post_save signal in your app/model:

https://docs.djangoproject.com/en/1.10/ref/signals/#post-save

Subito answered 31/3, 2017 at 17:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.