top of page

How to Use Django Signals Post Save and Post Delete?

Django is one of the popular Python Based open source web framework. It follows the MVT (Model View Template) architecture. Django is popular, Fast and Easy to learn.


Django provides most of built in features to handle the backend, server, database and frontend. You don't need any third party module for that.


There are various features that django provides like Views Function, Static and Media Files, Django signals, etc. One of the useful feature in Django Signals.


If you are working on Django project then, You have always faced to issue with the database that you won't get an alert whenevery any changes appears with the database. To resolve that issue Django signals comes in place.



What are Django Signals?


Django Signals is a strategy to allow decoupled applications to get notified when certain events occur. For example we can call django signals when new object is created, updated or deleted inside a database.


Today, I will tell you how you can use Django Signals Post Save and Post delete method in Django models.


How to use Django Signals Post Save and Post Delete?

To Start, first we need an existing Django Project with atleast on app.

1 . Open your Project in Code Editor.

2 . Go to your Apps Directory "myproject/app"

3 . Create a file named = "signals.py"

4. Import these modules

	from django.db.models.signals import post_save,post_delete
	#I have used django user model to use post save, post delete.
	from django.contrib.auth.models import User
	from django.dispatch import receiver

5. Now, Define these functions inside signals.py file.



@receiver(post_save,sender=User)
def create_profile(sender,instance,created,**kwargs):
    if created:
        #write your logic here
        print("User Profile Created")
        
@receiver(post_delete,sender=User)
def delete_profile(sender,instance,*args,**kwargs):
    #write your login when user profile is deleted.
    print("User Profile Deleted").
        

6. Now, In your apps directory, open apps.py file.

7. Define a new function just below the name = "app_name" line.



def ready(self):
        import accounts.signals #accounts is a name of app

8. Now, Migrate the app and You are ready to use Django signals.

9. Whenever your add a new object/row in Django User model from Admin panel or Frontend, Django Post save function will automatically start after save method is called.

9. Whenever you delete any object/row from django user model, Django post delete method will automatically start after delete method is called.





תגובות


bottom of page