Advertisement
horozov86

Signals in Django

Oct 23rd, 2024
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.71 KB | Source Code | 0 0
  1. # Signals
  2. 1. Create file signals.py
  3.  
  4. from django.contrib.auth import get_user_model
  5. from django.db.models.signals import post_save
  6. from django.dispatch import receiver
  7.  
  8. from petstagram.accounts.models import Profile
  9.  
  10. UserModel = get_user_model()
  11.  
  12. @receiver(post_save, sender=UserModel)
  13. def user_created(sender, instance, created, **kwargs):
  14.     if not created:
  15.         return
  16.  
  17.     Profile.objects.create(user=instance)
  18.  
  19. 2. In apps.py we have to write
  20.  
  21. from django.apps import AppConfig
  22.  
  23.  
  24. class AccountsConfig(AppConfig):
  25.     default_auto_field = "django.db.models.BigAutoField"
  26.     name = "my_project_name.accounts"
  27.  
  28.     def ready(self):
  29.         import my_project_name.accounts.accounts.signals
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement