Python django.db.models.signals() Examples

The following are 30 code examples for showing how to use django.db.models.signals(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.db.models , or try the search function .

Example 1
Project: django-rdf-io   Author: rob-metalinkage   File: manage.py    License: Creative Commons Zero v1.0 Universal 6 votes vote down vote up
def ctl_signals(request,cmd):
    """utility view to control and debug signals"""
    from rdf_io.signals import setup_signals,list_pubs,sync_signals
    if cmd == 'on':
        msg = auto_on()
    elif cmd == 'off' :
        msg = auto_off()
    elif cmd == 'list' :
        msg = list_pubs()
    elif cmd == 'sync' :
        msg = sync_signals()
    elif cmd == 'help' :
        msg = "usage /rdf_io/ctl_signals/(on|off|list|sync|help)"
    else:
        msg = "Command %s not understood. Use /rdf_io/ctl_signals/help for valid commands" % cmd
    return HttpResponse(msg, status=200) 
Example 2
Project: django-rdf-io   Author: rob-metalinkage   File: utils.py    License: Creative Commons Zero v1.0 Universal 6 votes vote down vote up
def list_pubs():
#    import pdb; pdb.set_trace()
    import weakref
    msg = []
    for receiver in signals.post_save.receivers:
        (receiver_class_name,_), receiver = receiver
        # django.contrib.contenttypes.generic.GenericForeignKey.instance_pre_init is not weakref
        if isinstance(receiver, weakref.ReferenceType):
            receiver = receiver()
        receiver = getattr(receiver, '__wraps__', receiver)
        receiver_name = getattr(receiver, '__name__', str(receiver))
        text = "%s.%s" % (receiver_class_name, receiver_name)
        if receiver_name == 'publish_rdf' :
            msg.append(text)

    return str(msg) 
Example 3
def register(self, serializer):
        """Store the serializer and model on registry to that the cache can be
        cleaned whenever an object is changed or deleted.
        After the serializer is registered we must connect the signals that
        clear the instance cache.
        """
        model = serializer.Meta.model

        if model not in self._registry:
            self._registry[model] = []

        if serializer in self._registry[model]:
            raise AlreadyRegistered("Serializer {} is already registered"
                                    .format(model.__name__))

        self._registry[model].append(serializer)
        self.connect_signals(model) 
Example 4
Project: allianceauth   Author: allianceauth   File: tests.py    License: GNU General Public License v2.0 6 votes vote down vote up
def setUp(self):
        # Inert signals before setup begins
        with mock.patch(MODULE_PATH + '.signals.trigger_all_ts_update') as trigger_all_ts_update:
            self.member = 'member_user'
            member = AuthUtils.create_member(self.member)
            Teamspeak3User.objects.create(user=member, uid=self.member, perm_key='123ABC')
            self.none_user = 'none_user'
            AuthUtils.create_user(self.none_user)
            state = member.profile.state
            ts_member_group = TSgroup.objects.create(ts_group_id=1, ts_group_name='Member')
            ts_state_group = TSgroup.objects.create(ts_group_id=2, ts_group_name='State')
            m2m_member_group = AuthTS.objects.create(auth_group=member.groups.all()[0])
            m2m_member_group.ts_group.add(ts_member_group)
            m2m_member_group.save()
            StateGroup.objects.create(state=state, ts_group=ts_state_group)
            self.service = Teamspeak3Service
            add_permissions() 
Example 5
Project: GTDWeb   Author: lanbing510   File: model_checks.py    License: GNU General Public License v2.0 5 votes vote down vote up
def check_model_signals(app_configs=None, **kwargs):
    """
    Ensure lazily referenced model signals senders are installed.
    """
    # Avoid circular import
    from django.db import models

    errors = []
    for name in dir(models.signals):
        obj = getattr(models.signals, name)
        if isinstance(obj, models.signals.ModelSignal):
            for reference, receivers in obj.unresolved_references.items():
                for receiver, _, _ in receivers:
                    # The receiver is either a function or an instance of class
                    # defining a `__call__` method.
                    if isinstance(receiver, types.FunctionType):
                        description = "The '%s' function" % receiver.__name__
                    else:
                        description = "An instance of the '%s' class" % receiver.__class__.__name__
                    errors.append(
                        Error(
                            "%s was connected to the '%s' signal "
                            "with a lazy reference to the '%s' sender, "
                            "which has not been installed." % (
                                description, name, '.'.join(reference)
                            ),
                            obj=receiver.__module__,
                            hint=None,
                            id='signals.E001'
                        )
                    )
    return errors 
Example 6
Project: django-softdelete-it   Author: exploreshaifali   File: models.py    License: MIT License 5 votes vote down vote up
def send_signal(self, model, instances, signal_type):
        '''
        Handle pre/post delete/save signal callings
        '''
        if not model._meta.auto_created:
            for obj in instances:
                if signal_type.__contains__('save'):
                    getattr(signals, signal_type).send(
                            sender=model, instance=obj,
                            created=False, using=self.using
                    )
                else:
                    getattr(signals, signal_type).send(
                            sender=model, instance=obj, using=self.using
                    ) 
Example 7
Project: django-db-mailer   Author: LPgenerator   File: signals.py    License: GNU General Public License v2.0 5 votes vote down vote up
def initial_signals():
    for signal in Signal.objects.filter(is_active=True):
        def_signal = getattr(signals, signal.signal)
        def_signal.connect(
            signal_receiver, sender=signal.model.model_class(),
            dispatch_uid=signal.model.name
        ) 
Example 8
Project: django-rdf-io   Author: rob-metalinkage   File: manage.py    License: Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def auto_on():
    """turn Auto push signals on"""
    from rdf_io.signals import setup_signals,list_pubs
    signals.post_save.connect(setup_signals, sender=ObjectMapping)
    return list_pubs() 
Example 9
Project: django-rdf-io   Author: rob-metalinkage   File: manage.py    License: Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def auto_off():
    """turn off all Auto push signals on"""
    from rdf_io.signals import clear_signals
    return clear_signals() 
Example 10
Project: django-rdf-io   Author: rob-metalinkage   File: utils.py    License: Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def sync_signals():
    """For each ObjectMapping force signal to be added or removed"""
    mappedObj = ObjectMapping.objects.all()
    for objmapping in mappedObj:
        _setup(objmapping)
    return "synced RDf publishing signals" 
Example 11
Project: django-rdf-io   Author: rob-metalinkage   File: utils.py    License: Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def _setup(objmapping) :
    try:
        if objmapping.auto_push :
            ct = ContentType.objects.get(id = objmapping.content_type_id).model_class()
            signals.post_save.connect(publish_rdf, sender=ct, dispatch_uid=str(ct.__name__))
            print("RDF publishing configured for model {}".format((ct)))
            logger.info(
                "RDF publishing configured for model {}".format((ct)))
    except Exception as e:
        print("Error trying to set up auto-publish for object mapping.. %s " % e)
        pass 
Example 12
Project: django-rdf-io   Author: rob-metalinkage   File: utils.py    License: Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def _clear(objmapping) :
    try:
        if objmapping.auto_push :
            ct = ContentType.objects.get(id = objmapping.content_type_id).model_class()
            signals.post_save.disconnect(publish_rdf, sender=ct, dispatch_uid=str(ct.__name__))
            print("RDF publishing un-configured for model {}".format((ct)))
            logger.info(
                "RDF publishing un-configured for model {}".format((ct)))
    except Exception as e:
        print("Error trying to clear auto-publish for object mapping.. %s " % e)
        pass 
Example 13
def connect_signals(self, model):
        from .signals import clear_instance # NOQA - Prevent circular import

        signals.post_save.connect(clear_instance, sender=model)
        signals.pre_delete.connect(clear_instance, sender=model) 
Example 14
Project: elasticsearch-django   Author: yunojuno   File: apps.py    License: MIT License 5 votes vote down vote up
def ready(self) -> None:
        """Validate config and connect signals."""
        super(ElasticAppConfig, self).ready()
        _validate_config(bool(settings.get_setting("strict_validation")))
        _connect_signals() 
Example 15
Project: elasticsearch-django   Author: yunojuno   File: apps.py    License: MIT License 5 votes vote down vote up
def _connect_signals() -> None:
    """Connect up post_save, post_delete signals for models."""
    for index in settings.get_index_names():
        for model in settings.get_index_models(index):
            _connect_model_signals(model) 
Example 16
Project: elasticsearch-django   Author: yunojuno   File: apps.py    License: MIT License 5 votes vote down vote up
def _connect_model_signals(model: Type[Model]) -> None:
    """Connect signals for a single model."""
    dispatch_uid = "%s.post_save" % model._meta.model_name
    logger.debug("Connecting search index model post_save signal: %s", dispatch_uid)
    signals.post_save.connect(_on_model_save, sender=model, dispatch_uid=dispatch_uid)
    dispatch_uid = "%s.post_delete" % model._meta.model_name
    logger.debug("Connecting search index model post_delete signal: %s", dispatch_uid)
    signals.post_delete.connect(
        _on_model_delete, sender=model, dispatch_uid=dispatch_uid
    ) 
Example 17
Project: bungiesearch   Author: ChristopherRabotin   File: signals.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_signal_processor():
    signals = Bungiesearch.BUNGIE['SIGNALS']
    if 'SIGNAL_CLASS' in signals:
        signal_path = signals['SIGNAL_CLASS'].split('.')
        signal_module = import_module('.'.join(signal_path[:-1]))
        signal_class = getattr(signal_module, signal_path[-1])
    else:
        signal_class = BungieSignalProcessor
    return signal_class() 
Example 18
Project: bungiesearch   Author: ChristopherRabotin   File: signals.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setup(self, model):
        signals.post_save.connect(self.post_save_connector, sender=model)
        signals.pre_delete.connect(self.pre_delete_connector, sender=model) 
Example 19
Project: bungiesearch   Author: ChristopherRabotin   File: signals.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def teardown(self, model):
        signals.pre_delete.disconnect(self.pre_delete_connector, sender=model)
        signals.post_save.disconnect(self.post_save_connector, sender=model) 
Example 20
Project: django-htk   Author: hacktoolkit   File: apps.py    License: MIT License 5 votes vote down vote up
def ready(self):
        ##
        # signals
        UserModel = get_user_model()
        from htk.apps.accounts.models import UserEmail

        # Upon saving a User object, create a UserProfile object if it doesn't already exist
        signals.post_save.connect(create_user_profile, sender=UserModel, dispatch_uid='htk_create_user_profile')
        # See AUTH_PROFILE_MODULE in settings.py

        signals.pre_delete.connect(pre_delete_user, sender=UserModel, dispatch_uid='htk_pre_delete_user')

        signals.post_save.connect(process_user_email_association, sender=UserEmail, dispatch_uid='htk_process_user_email_association') 
Example 21
Project: django-htk   Author: hacktoolkit   File: apps.py    License: MIT License 5 votes vote down vote up
def ready(self):
        GroupQuoteModel = resolve_model_dynamically(htk_setting('HTK_CPQ_GROUP_QUOTE_MODEL'))

        ##
        # signals
        signals.post_save.connect(sync_group_sub_quotes, sender=GroupQuoteModel) 
Example 22
Project: django-sqlserver   Author: denisenkom   File: tests.py    License: MIT License 5 votes vote down vote up
def test_database_arg_save_and_delete(self):
        """
        The pre/post_save signal contains the correct database.
        """
        # Make some signal receivers
        pre_save_receiver = DatabaseReceiver()
        post_save_receiver = DatabaseReceiver()
        pre_delete_receiver = DatabaseReceiver()
        post_delete_receiver = DatabaseReceiver()
        # Make model and connect receivers
        signals.pre_save.connect(sender=Person, receiver=pre_save_receiver)
        signals.post_save.connect(sender=Person, receiver=post_save_receiver)
        signals.pre_delete.connect(sender=Person, receiver=pre_delete_receiver)
        signals.post_delete.connect(sender=Person, receiver=post_delete_receiver)
        p = Person.objects.create(name='Darth Vader')
        # Save and test receivers got calls
        p.save()
        self.assertEqual(pre_save_receiver._database, DEFAULT_DB_ALIAS)
        self.assertEqual(post_save_receiver._database, DEFAULT_DB_ALIAS)
        # Delete, and test
        p.delete()
        self.assertEqual(pre_delete_receiver._database, DEFAULT_DB_ALIAS)
        self.assertEqual(post_delete_receiver._database, DEFAULT_DB_ALIAS)
        # Save again to a different database
        p.save(using="other")
        self.assertEqual(pre_save_receiver._database, "other")
        self.assertEqual(post_save_receiver._database, "other")
        # Delete, and test
        p.delete(using="other")
        self.assertEqual(pre_delete_receiver._database, "other")
        self.assertEqual(post_delete_receiver._database, "other")

        signals.pre_save.disconnect(sender=Person, receiver=pre_save_receiver)
        signals.post_save.disconnect(sender=Person, receiver=post_save_receiver)
        signals.pre_delete.disconnect(sender=Person, receiver=pre_delete_receiver)
        signals.post_delete.disconnect(sender=Person, receiver=post_delete_receiver) 
Example 23
Project: django_audit_trail   Author: TriplePoint-Software   File: watcher.py    License: Apache License 2.0 5 votes vote down vote up
def init_signals(self):
        signals.post_save.connect(self.on_post_save_create, sender=self.model_class, weak=False)
        signals.post_init.connect(self.on_post_init, sender=self.model_class, weak=False)
        signals.post_save.connect(self.on_post_save_update, sender=self.model_class, weak=False)
        signals.pre_delete.connect(self.on_pre_delete, sender=self.model_class, weak=False)
        signals.post_delete.connect(self.on_post_delete, sender=self.model_class, weak=False)

        self.init_related_signals() 
Example 24
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_database_arg_save_and_delete(self):
        """
        The pre/post_save signal contains the correct database.
        """
        # Make some signal receivers
        pre_save_receiver = DatabaseReceiver()
        post_save_receiver = DatabaseReceiver()
        pre_delete_receiver = DatabaseReceiver()
        post_delete_receiver = DatabaseReceiver()
        # Make model and connect receivers
        signals.pre_save.connect(sender=Person, receiver=pre_save_receiver)
        signals.post_save.connect(sender=Person, receiver=post_save_receiver)
        signals.pre_delete.connect(sender=Person, receiver=pre_delete_receiver)
        signals.post_delete.connect(sender=Person, receiver=post_delete_receiver)
        p = Person.objects.create(name='Darth Vader')
        # Save and test receivers got calls
        p.save()
        self.assertEqual(pre_save_receiver._database, DEFAULT_DB_ALIAS)
        self.assertEqual(post_save_receiver._database, DEFAULT_DB_ALIAS)
        # Delete, and test
        p.delete()
        self.assertEqual(pre_delete_receiver._database, DEFAULT_DB_ALIAS)
        self.assertEqual(post_delete_receiver._database, DEFAULT_DB_ALIAS)
        # Save again to a different database
        p.save(using="other")
        self.assertEqual(pre_save_receiver._database, "other")
        self.assertEqual(post_save_receiver._database, "other")
        # Delete, and test
        p.delete(using="other")
        self.assertEqual(pre_delete_receiver._database, "other")
        self.assertEqual(post_delete_receiver._database, "other")

        signals.pre_save.disconnect(sender=Person, receiver=pre_save_receiver)
        signals.post_save.disconnect(sender=Person, receiver=post_save_receiver)
        signals.pre_delete.disconnect(sender=Person, receiver=pre_delete_receiver)
        signals.post_delete.disconnect(sender=Person, receiver=post_delete_receiver) 
Example 25
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_database_arg_save_and_delete(self):
        """
        The pre/post_save signal contains the correct database.
        """
        # Make some signal receivers
        pre_save_receiver = DatabaseReceiver()
        post_save_receiver = DatabaseReceiver()
        pre_delete_receiver = DatabaseReceiver()
        post_delete_receiver = DatabaseReceiver()
        # Make model and connect receivers
        signals.pre_save.connect(sender=Person, receiver=pre_save_receiver)
        signals.post_save.connect(sender=Person, receiver=post_save_receiver)
        signals.pre_delete.connect(sender=Person, receiver=pre_delete_receiver)
        signals.post_delete.connect(sender=Person, receiver=post_delete_receiver)
        p = Person.objects.create(name='Darth Vader')
        # Save and test receivers got calls
        p.save()
        self.assertEqual(pre_save_receiver._database, DEFAULT_DB_ALIAS)
        self.assertEqual(post_save_receiver._database, DEFAULT_DB_ALIAS)
        # Delete, and test
        p.delete()
        self.assertEqual(pre_delete_receiver._database, DEFAULT_DB_ALIAS)
        self.assertEqual(post_delete_receiver._database, DEFAULT_DB_ALIAS)
        # Save again to a different database
        p.save(using="other")
        self.assertEqual(pre_save_receiver._database, "other")
        self.assertEqual(post_save_receiver._database, "other")
        # Delete, and test
        p.delete(using="other")
        self.assertEqual(pre_delete_receiver._database, "other")
        self.assertEqual(post_delete_receiver._database, "other")

        signals.pre_save.disconnect(sender=Person, receiver=pre_save_receiver)
        signals.post_save.disconnect(sender=Person, receiver=post_save_receiver)
        signals.pre_delete.disconnect(sender=Person, receiver=pre_delete_receiver)
        signals.post_delete.disconnect(sender=Person, receiver=post_delete_receiver) 
Example 26
Project: mapstory   Author: MapStory   File: populate_test_data.py    License: GNU General Public License v3.0 5 votes vote down vote up
def disconnect_signals():
    """Disconnect signals for test class purposes."""
    from django.db.models import signals
    from geonode.geoserver.signals import geoserver_pre_save_maplayer
    from geonode.geoserver.signals import geoserver_post_save_map
    from geonode.geoserver.signals import geoserver_pre_save
    from geonode.geoserver.signals import geoserver_post_save
    signals.pre_save.disconnect(geoserver_pre_save_maplayer, sender=MapLayer)
    signals.post_save.disconnect(geoserver_post_save_map, sender=Map)
    signals.pre_save.disconnect(geoserver_pre_save, sender=Layer)
    signals.post_save.disconnect(geoserver_post_save, sender=Layer) 
Example 27
Project: mapstory   Author: MapStory   File: populate_test_data.py    License: GNU General Public License v3.0 5 votes vote down vote up
def reconnect_signals():
    """Reconnect signals for test class purposes."""
    from django.db.models import signals
    from geonode.geoserver.signals import geoserver_pre_save_maplayer
    from geonode.geoserver.signals import geoserver_post_save_map
    from geonode.geoserver.signals import geoserver_pre_save
    from geonode.geoserver.signals import geoserver_post_save
    signals.pre_save.connect(geoserver_pre_save_maplayer, sender=MapLayer)
    signals.post_save.connect(geoserver_post_save_map, sender=Map)
    signals.pre_save.connect(geoserver_pre_save, sender=Layer)
    signals.post_save.connect(geoserver_post_save, sender=Layer) 
Example 28
Project: allianceauth   Author: allianceauth   File: tests.py    License: GNU General Public License v2.0 5 votes vote down vote up
def setUp(self):
        # Inert signals before setup begins
        with mock.patch(MODULE_PATH + '.signals.trigger_all_ts_update') as trigger_all_ts_update:
            self.member = AuthUtils.create_member('auth_member')
            self.member.email = 'auth_member@example.com'
            self.member.save()
            AuthUtils.add_main_character(self.member, 'auth_member', '12345', corp_id='111', corp_name='Test Corporation')

            ts_member_group = TSgroup.objects.create(ts_group_id=1, ts_group_name='Member')
            m2m_member = AuthTS.objects.create(auth_group=Group.objects.get(name='Member'))
            m2m_member.ts_group.add(ts_member_group)
            m2m_member.save()
            add_permissions() 
Example 29
Project: allianceauth   Author: allianceauth   File: tests.py    License: GNU General Public License v2.0 5 votes vote down vote up
def setUp(self):
        self.member = AuthUtils.create_member('auth_member')

        # Suppress signals action while setting up
        with mock.patch(MODULE_PATH + '.signals.trigger_all_ts_update') as trigger_all_ts_update:
            ts_member_group = TSgroup.objects.create(ts_group_id=1, ts_group_name='Member')
            self.m2m_member = AuthTS.objects.create(auth_group=Group.objects.get(name='Member'))
            self.m2m_member.ts_group.add(ts_member_group)
            self.m2m_member.save() 
Example 30
Project: allianceauth   Author: allianceauth   File: tests.py    License: GNU General Public License v2.0 5 votes vote down vote up
def test_m2m_signal_registry(self):
        """
        Test that the m2m signal has been registered
        """
        registered_functions = [r[1]() for r in signals.m2m_changed.receivers]
        self.assertIn(m2m_changed_authts_group, registered_functions)