i am using django default receiver to handle signal. but its not working. i have modified User model in APP1 whenver new User object create a receiver in APP2 signal.py is listen to it, but its not working.
class User(BaseModel, AbstractBaseUser, PermissionsMixin):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
username = models.CharField(max_length=40, unique=True)
first_name = models.CharField(max_length=30, blank=True, null=True)
last_name = models.CharField(max_length=30, blank=True, null=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_email_verified = models.BooleanField(default=False)
is_paid = models.IntegerField(default=0)
access_token = models.CharField(max_length=128, blank=True)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
class Meta:
db_table = 'users'
def __str__(self):
return self.email
from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from accounts.models import User
@receiver(post_save, sender=User)#settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
print ("token generated")
if created:
print("data at signal ****", instance.email, instance)
There are 3 types of signal. pre_save/post_save: This signal works before/after the method save(). pre_delete/post_delete: This signal works before after delete a model's instance (method delete()) this signal is thrown.
There are two ways to send signals in Django. To send a signal, call either Signal. send() (all built-in signals use this) or Signal.
Finally I got the answer. Its because I'm not importing signals.py on startup.
from __future__ import unicode_literals
from django.apps import AppConfig
class StreamsConfig(AppConfig):
name = 'streams'
def ready(self):
print("at ready")
import streams.signals
default_app_config = 'streams.apps.StreamsConfig'
after this change I'm receiving signals
Update:
As per django 3.0 documentation for newer applications adding default_app_config in init.py is not required if you are using dotted path to application configuration. https://docs.djangoproject.com/en/3.0/ref/applications/#django.apps.AppConfig.ready
Just replace
INSTALLED_APPS = (
...,
'streams',
)
with
INSTALLED_APPS = (
...,
'streams.apps.StreamsConfig',
)
It will work.
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