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?
The save method is an inherited method from models. Model which is executed to save an instance into a particular Model. Whenever one tries to create an instance of a model either from admin interface or django shell, save() function is run.
Creating objects To create a new instance of a model, instantiate it like any other Python class: class Model (**kwargs) The keyword arguments are the names of the fields you've defined on your model. Note that instantiating a model in no way touches your database; for that, you need to save() .
save() calls the clean. This way the integrity is enforced both from forms and from other calling code, the command line, and tests. Without this, there is (AFAICT) no way to write a test that ensures that a model has a FK relation to a specifically chosen (not default) other model.
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.
Maybe you can use post_save signal in your app/model:
https://docs.djangoproject.com/en/1.10/ref/signals/#post-save
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With