Skip to content Skip to sidebar Skip to footer

How To Trigger Custom Python Code When A Valid Django Form Is Saved In The Database

Django newbie here, I created a simple form following this tutorial, and my form correctly saves the data in my Postgres connected local database. I was wondering, how can I trigge

Solution 1:

what you want to use here is signals. A signal is some function that gets executed after an item is added or updated in your data base. Assuming your model you want to connect to is called "MyModel" do this:

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


@receiver(post_save, sender=MyModel)defmy_handler(sender, instance, created, **kwargs):
    if created:
        # run your custom code HERE

instance is what was inserted / updated, created is boolean indicating if this was an update or insert.

docs: https://docs.djangoproject.com/en/2.1/topics/signals/

Post a Comment for "How To Trigger Custom Python Code When A Valid Django Form Is Saved In The Database"