Python django.db.models.signals.post_save.connect() Examples

The following are 30 code examples of django.db.models.signals.post_save.connect(). 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 also want to check out all available functions/classes of the module django.db.models.signals.post_save , or try the search function .
Example #1
Source File: signal.py    From mercure with GNU General Public License v3.0 6 votes vote down vote up
def test_attachment_executed(self):
        def handler(instance, **kwarg):
            # get post on landing page event
            if instance.target_tracker.key != TRACKER_ATTACHMENT_EXECUTED:
                # ignore other target event
                return

            self.assertEqual(instance.ip, '127.0.0.1')
            self.assertEqual(instance.user_agent, 'Outlook')
            raise SuccessException()

        post_save.connect(handler, sender=TrackerInfos)

        # call tracker
        self.send_campaign()
        attachment = json.loads(mail.outbox[-1].attachments[0][1].decode())
        tracker_url = attachment['tracker_url']

        # test if handler has call
        with self.assertRaises(SuccessException):
            self.client.defaults['HTTP_USER_AGENT'] = 'Outlook'
            self.client.get(tracker_url)

        # clean
        self.assertTrue(post_save.disconnect(handler, sender=TrackerInfos)) 
Example #2
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_empty_update_fields(self):
        s = Person.objects.create(name='Sara', gender='F')
        pre_save_data = []

        def pre_save_receiver(**kwargs):
            pre_save_data.append(kwargs['update_fields'])
        pre_save.connect(pre_save_receiver)
        post_save_data = []

        def post_save_receiver(**kwargs):
            post_save_data.append(kwargs['update_fields'])
        post_save.connect(post_save_receiver)
        # Save is skipped.
        with self.assertNumQueries(0):
            s.save(update_fields=[])
        # Signals were skipped, too...
        self.assertEqual(len(pre_save_data), 0)
        self.assertEqual(len(post_save_data), 0)

        pre_save.disconnect(pre_save_receiver)
        post_save.disconnect(post_save_receiver) 
Example #3
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_update_fields_signals(self):
        p = Person.objects.create(name='Sara', gender='F')
        pre_save_data = []

        def pre_save_receiver(**kwargs):
            pre_save_data.append(kwargs['update_fields'])
        pre_save.connect(pre_save_receiver)
        post_save_data = []

        def post_save_receiver(**kwargs):
            post_save_data.append(kwargs['update_fields'])
        post_save.connect(post_save_receiver)
        p.save(update_fields=['name'])
        self.assertEqual(len(pre_save_data), 1)
        self.assertEqual(len(pre_save_data[0]), 1)
        self.assertIn('name', pre_save_data[0])
        self.assertEqual(len(post_save_data), 1)
        self.assertEqual(len(post_save_data[0]), 1)
        self.assertIn('name', post_save_data[0])

        pre_save.disconnect(pre_save_receiver)
        post_save.disconnect(post_save_receiver) 
Example #4
Source File: model_observer.py    From djangochannelsrestframework with MIT License 6 votes vote down vote up
def _connect(self):
        """
        Connect the signal listing.
        """

        # this is used to capture the current state for the model
        post_init.connect(
            self.post_init_receiver, sender=self.model_cls, dispatch_uid=id(self)
        )

        post_save.connect(
            self.post_save_receiver, sender=self.model_cls, dispatch_uid=id(self)
        )

        post_delete.connect(
            self.post_delete_receiver, sender=self.model_cls, dispatch_uid=id(self)
        ) 
Example #5
Source File: apps.py    From telemetry-analysis-service with Mozilla Public License 2.0 6 votes vote down vote up
def ready(self):
        # The app is now ready. Include any monkey patches here.

        # Monkey patch CSRF to switch to session based CSRF. Session
        # based CSRF will prevent attacks from apps under the same
        # domain. If you're planning to host your app under it's own
        # domain you can remove session_csrf and use Django's CSRF
        # library. See also
        # https://github.com/mozilla/sugardough/issues/38
        session_csrf.monkeypatch()

        # Connect signals.
        from atmo.jobs.models import SparkJob
        from atmo.jobs.signals import assign_group_perm, remove_group_perm

        post_save.connect(
            assign_group_perm,
            sender=SparkJob,
            dispatch_uid="sparkjob_post_save_assign_perm",
        )
        pre_delete.connect(
            remove_group_perm,
            sender=SparkJob,
            dispatch_uid="sparkjob_pre_delete_remove_perm",
        ) 
Example #6
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_update_fields_signals(self):
        p = Person.objects.create(name='Sara', gender='F')
        pre_save_data = []

        def pre_save_receiver(**kwargs):
            pre_save_data.append(kwargs['update_fields'])
        pre_save.connect(pre_save_receiver)
        post_save_data = []

        def post_save_receiver(**kwargs):
            post_save_data.append(kwargs['update_fields'])
        post_save.connect(post_save_receiver)
        p.save(update_fields=['name'])
        self.assertEqual(len(pre_save_data), 1)
        self.assertEqual(len(pre_save_data[0]), 1)
        self.assertIn('name', pre_save_data[0])
        self.assertEqual(len(post_save_data), 1)
        self.assertEqual(len(post_save_data[0]), 1)
        self.assertIn('name', post_save_data[0])

        pre_save.disconnect(pre_save_receiver)
        post_save.disconnect(post_save_receiver) 
Example #7
Source File: signal.py    From mercure with GNU General Public License v3.0 6 votes vote down vote up
def test_edit_campaign_report_item(self):
        def handler(context, **kwarg):
            context['tabs_layout']['Test'] = context['tabs_layout']. \
                pop('Other')

        make_campaign_report.connect(handler)

        # test
        content = self.get()
        self.assertIn('<a href="#test" aria-controls="test" role="tab" '
                      'data-toggle="tab">Test</a>', content)
        self.assertIn('id="test"', content)
        self.assertNotIn('<a href="#other" aria-controls="other" '
                         'role="tab" data-toggle="tab">Other</a>', content)
        self.assertNotIn('id="other"', content)

        # clean
        self.assertTrue(make_campaign_report.disconnect(handler)) 
Example #8
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_empty_update_fields(self):
        s = Person.objects.create(name='Sara', gender='F')
        pre_save_data = []

        def pre_save_receiver(**kwargs):
            pre_save_data.append(kwargs['update_fields'])
        pre_save.connect(pre_save_receiver)
        post_save_data = []

        def post_save_receiver(**kwargs):
            post_save_data.append(kwargs['update_fields'])
        post_save.connect(post_save_receiver)
        # Save is skipped.
        with self.assertNumQueries(0):
            s.save(update_fields=[])
        # Signals were skipped, too...
        self.assertEqual(len(pre_save_data), 0)
        self.assertEqual(len(post_save_data), 0)

        pre_save.disconnect(pre_save_receiver)
        post_save.disconnect(post_save_receiver) 
Example #9
Source File: state.py    From django-river with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def contribute_to_class(self, cls, name, *args, **kwargs):
        @classproperty
        def river(_self):
            return RiverObject(_self)

        self.field_name = name

        self._add_to_class(cls, self.field_name + "_transition_approvals",
                           GenericRelation('%s.%s' % (TransitionApproval._meta.app_label, TransitionApproval._meta.object_name)))
        self._add_to_class(cls, self.field_name + "_transitions", GenericRelation('%s.%s' % (Transition._meta.app_label, Transition._meta.object_name)))

        if id(cls) not in workflow_registry.workflows:
            self._add_to_class(cls, "river", river)

        super(StateField, self).contribute_to_class(cls, name, *args, **kwargs)

        if id(cls) not in workflow_registry.workflows:
            post_save.connect(_on_workflow_object_saved, self.model, False, dispatch_uid='%s_%s_riverstatefield_post' % (self.model, name))
            post_delete.connect(_on_workflow_object_deleted, self.model, False, dispatch_uid='%s_%s_riverstatefield_post' % (self.model, name))

        workflow_registry.add(self.field_name, cls) 
Example #10
Source File: signal.py    From mercure with GNU General Public License v3.0 6 votes vote down vote up
def test_email_open(self):
        def handler(instance, **kwarg):
            # get email open event
            if instance.target_tracker.key != TRACKER_EMAIL_OPEN:
                # ignore other target event
                return

            self.assertEqual(instance.ip, '127.0.0.1')
            self.assertEqual(instance.user_agent, 'Outlook')
            raise SuccessException()

        post_save.connect(handler, sender=TrackerInfos)

        # call tracker
        self.send_campaign()
        mail_html = mail.outbox[-1].alternatives[0][0]
        tracker_url = mail_html.split('src="')[-1].split('"')[0]

        # test if handler has call
        with self.assertRaises(SuccessException):
            self.client.defaults['HTTP_USER_AGENT'] = 'Outlook'
            self.client.get(tracker_url)

        # clean
        self.assertTrue(post_save.disconnect(handler, sender=TrackerInfos)) 
Example #11
Source File: signal.py    From mercure with GNU General Public License v3.0 6 votes vote down vote up
def test_add_item(self):
        # add value handler
        def handler(urls, **kwarg):
            urls.append({
                'name': 'test',
                'url': 'http://google.fr',
            })

        make_menu.connect(handler)

        # test
        item = self.get('test')
        self.assertIsNotNone(item)
        self.assertEqual(item['url'], 'http://google.fr')

        # clean
        self.assertTrue(make_menu.disconnect(handler)) 
Example #12
Source File: mixins.py    From django-knocker with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _connect(cls):
        """
        Connect signal to current model
        """
        pre_save.connect(
            notify_items_pre_save, sender=cls,
            dispatch_uid='knocker_pre_save_{0}'.format(cls.__name__)
        )
        post_save.connect(
            notify_items_post_save, sender=cls,
            dispatch_uid='knocker_post_save_{0}'.format(cls.__name__)
        )
        pre_delete.connect(
            notify_items_pre_delete, sender=cls,
            dispatch_uid='knocker_pre_delete_{0}'.format(cls.__name__)
        )
        post_delete.connect(
            notify_items_post_delete, sender=cls,
            dispatch_uid='knocker_post_delete_{0}'.format(cls.__name__)
        ) 
Example #13
Source File: signal.py    From mercure with GNU General Public License v3.0 6 votes vote down vote up
def test_delete_vars(self):
        # add value handler
        def handler(vars_data, **kwarg):
            var_data = self._search_name(vars_data, 'email')
            self.assertIsNotNone(var_data)
            vars_data.remove(var_data)

        make_template_vars.connect(handler)

        # test value
        var_data = self.get('email')
        self.assertIsNone(var_data)

        # test replace
        content = replace_template_vars('{{ email }}')
        self.assertEqual(content, '{{ email }}')

        # clean
        self.assertTrue(make_template_vars.disconnect(handler)) 
Example #14
Source File: registration.py    From algoliasearch-django with MIT License 6 votes vote down vote up
def register(self, model, index_cls=AlgoliaIndex, auto_indexing=None):
        """
        Registers the given model with Algolia engine.

        If the given model is already registered with Algolia engine, a
        RegistrationError will be raised.
        """
        # Check for existing registration.
        if self.is_registered(model):
            raise RegistrationError(
                '{} is already registered with Algolia engine'.format(model))

        # Perform the registration.
        if not issubclass(index_cls, AlgoliaIndex):
            raise RegistrationError(
                '{} should be a subclass of AlgoliaIndex'.format(index_cls))
        index_obj = index_cls(model, self.client, self.__settings)
        self.__registered_models[model] = index_obj

        if (isinstance(auto_indexing, bool) and
                auto_indexing) or self.__auto_indexing:
            # Connect to the signalling framework.
            post_save.connect(self.__post_save_receiver, model)
            pre_delete.connect(self.__pre_delete_receiver, model)
            logger.info('REGISTER %s', model) 
Example #15
Source File: signal.py    From mercure with GNU General Public License v3.0 6 votes vote down vote up
def test_edit_vars(self):
        # add value handler
        def handler(vars_data, **kwarg):
            var_data = self._search_name(vars_data, 'email')
            self.assertIsNotNone(var_data)
            var_data['value'] = 'Hello Word!'

        make_template_vars.connect(handler)

        # test value
        var_data = self.get('email')
        self.assertIsNotNone(var_data)
        self.assertEqual(var_data['value'], 'Hello Word!')

        # test replace
        content = replace_template_vars('{{ email }}')
        self.assertEqual(content, 'Hello Word!')

        # clean
        self.assertTrue(make_template_vars.disconnect(handler)) 
Example #16
Source File: signal.py    From mercure with GNU General Public License v3.0 6 votes vote down vote up
def test_add_vars(self):
        # add value handler
        def handler(vars_data, **kwarg):
            vars_data.append({
                'name': 'test_var',
                'description': 'Is a test!',
                'value': 'Hello!',
            })

        make_template_vars.connect(handler)

        # test value
        var_data = self.get('test_var')
        self.assertIsNotNone(var_data)
        self.assertEqual(var_data['value'], 'Hello!')
        self.assertEqual(var_data['description'], 'Is a test!')

        # test replace
        content = replace_template_vars('{{ test_var }}')
        self.assertEqual(content, 'Hello!')

        # clean
        self.assertTrue(make_template_vars.disconnect(handler)) 
Example #17
Source File: apps.py    From openwisp-controller with GNU General Public License v3.0 6 votes vote down vote up
def ready(self):
        """
        connects the ``config_modified`` signal
        to the ``update_config`` celery task
        which will be executed in the background
        """
        config_modified.connect(
            self.config_modified_receiver, dispatch_uid='connection.update_config'
        )
        Config = load_model('config', 'Config')
        Credentials = load_model('connection', 'Credentials')
        post_save.connect(
            Credentials.auto_add_credentials_to_device,
            sender=Config,
            dispatch_uid='connection.auto_add_credentials',
        ) 
Example #18
Source File: signals.py    From django-collaborative with MIT License 6 votes vote down vote up
def setup_dynmodel_signals():
    """
    Attach signals to our dynamically generated models. Here, we
    only attach dynamically-generated signals to non-CSV backed
    models.
    """
    logger.debug("Setting up dynamic model signals...")
    models.DynamicModel._POST_SAVE_SIGNALS.append(build_and_link_metadata_fk)
    for dynmodel in models.DynamicModel.objects.all():
        if dynmodel.get_attr("type") != MODEL_TYPES.CSV:
            logger.debug("Skipping non-CSV model for signal: %s" % dynmodel)
            continue
        Model = getattr(models, dynmodel.name)
        logger.debug("Attaching post-save signal to dynmodel: %s model: %s" % (
            dynmodel, Model
        ))
        post_save.connect(attach_blank_meta_to_record, sender=Model) 
Example #19
Source File: tests.py    From django-sqlserver with MIT License 6 votes vote down vote up
def test_update_fields_signals(self):
        p = Person.objects.create(name='Sara', gender='F')
        pre_save_data = []

        def pre_save_receiver(**kwargs):
            pre_save_data.append(kwargs['update_fields'])
        pre_save.connect(pre_save_receiver)
        post_save_data = []

        def post_save_receiver(**kwargs):
            post_save_data.append(kwargs['update_fields'])
        post_save.connect(post_save_receiver)
        p.save(update_fields=['name'])
        self.assertEqual(len(pre_save_data), 1)
        self.assertEqual(len(pre_save_data[0]), 1)
        self.assertIn('name', pre_save_data[0])
        self.assertEqual(len(post_save_data), 1)
        self.assertEqual(len(post_save_data[0]), 1)
        self.assertIn('name', post_save_data[0])

        pre_save.disconnect(pre_save_receiver)
        post_save.disconnect(post_save_receiver) 
Example #20
Source File: tests.py    From django-sqlserver with MIT License 6 votes vote down vote up
def test_empty_update_fields(self):
        s = Person.objects.create(name='Sara', gender='F')
        pre_save_data = []

        def pre_save_receiver(**kwargs):
            pre_save_data.append(kwargs['update_fields'])
        pre_save.connect(pre_save_receiver)
        post_save_data = []

        def post_save_receiver(**kwargs):
            post_save_data.append(kwargs['update_fields'])
        post_save.connect(post_save_receiver)
        # Save is skipped.
        with self.assertNumQueries(0):
            s.save(update_fields=[])
        # Signals were skipped, too...
        self.assertEqual(len(pre_save_data), 0)
        self.assertEqual(len(post_save_data), 0)

        pre_save.disconnect(pre_save_receiver)
        post_save.disconnect(post_save_receiver) 
Example #21
Source File: signals.py    From edx-enterprise with GNU Affero General Public License v3.0 6 votes vote down vote up
def create_enterprise_enrollment_receiver(sender, instance, **kwargs):     # pylint: disable=unused-argument
    """
    Watches for post_save signal for creates on the CourseEnrollment table.

    Spin off an async task to generate an EnterpriseCourseEnrollment if appropriate.
    """
    if kwargs.get('created') and instance.user:
        user_id = instance.user.id
        try:
            ecu = EnterpriseCustomerUser.objects.get(user_id=user_id)
        except ObjectDoesNotExist:
            return
        logger.info((
            "User %s is an EnterpriseCustomerUser. "
            "Spinning off task to check if course is within User's "
            "Enterprise's EnterpriseCustomerCatalog."
        ), user_id)

        create_enterprise_enrollment.delay(
            str(instance.course_id),
            ecu.id,
        )


# Don't connect this receiver if we dont have access to CourseEnrollment model 
Example #22
Source File: signal.py    From mercure with GNU General Public License v3.0 5 votes vote down vote up
def test_email_send(self):
        def handler(instance, **kwarg):
            # get email open event
            if instance.key != TRACKER_EMAIL_SEND:
                # ignore other target event
                return

            self.assertEqual(instance.value, 'success')

            # add entry on db for set test in success => SuccessException make
            # infinite loop
            TrackerInfos.objects.create(
                target_tracker=instance,
                raw='handler_%s_test_ok' % TRACKER_EMAIL_SEND
            )

        post_save.connect(handler, sender=Tracker)

        # send mail
        campaign = self.send_campaign()

        # test if handler has call
        raw = 'handler_%s_test_ok' % TRACKER_EMAIL_SEND
        test_result_tracker = TrackerInfos.objects.filter(raw=raw).first()
        self.assertIsNotNone(test_result_tracker)
        tracker = test_result_tracker.target_tracker
        self.assertEqual(campaign.pk, tracker.campaign.pk)
        self.assertEqual(TRACKER_EMAIL_SEND, tracker.key)

        # clean
        self.assertTrue(post_save.disconnect(handler, sender=Tracker)) 
Example #23
Source File: apps.py    From Inboxen with GNU Affero General Public License v3.0 5 votes vote down vote up
def ready(self):
        Question = self.get_model("Question")
        post_save.connect(signals.new_question, sender=Question, dispatch_uid="question notifier") 
Example #24
Source File: apps.py    From Kiwi with GNU General Public License v2.0 5 votes vote down vote up
def ready(self):
        from .models import Bug
        from .management import create_permissions
        from tcms import signals

        post_save.connect(signals.handle_emails_post_bug_save, sender=Bug)
        post_migrate.connect(
            create_permissions,
            dispatch_uid="tcms.bugs.management.create_permissions"
        ) 
Example #25
Source File: __init__.py    From allianceauth with GNU General Public License v2.0 5 votes vote down vote up
def connect_signals():
    post_save.connect(receiver=reassess_on_profile_save, sender=UserProfile)
    pre_save.connect(receiver=signals.pre_save_config, sender=AutogroupsConfig)
    pre_delete.connect(receiver=signals.pre_delete_config, sender=AutogroupsConfig)
    post_save.connect(receiver=signals.check_groups_on_profile_update, sender=UserProfile)
    m2m_changed.connect(receiver=signals.autogroups_states_changed, sender=AutogroupsConfig.states.through) 
Example #26
Source File: auth_utils.py    From allianceauth with GNU General Public License v2.0 5 votes vote down vote up
def connect_signals(cls):
        m2m_changed.connect(m2m_changed_user_groups, sender=User.groups.through)
        m2m_changed.connect(m2m_changed_group_permissions, sender=Group.permissions.through)
        m2m_changed.connect(m2m_changed_user_permissions, sender=User.user_permissions.through)
        m2m_changed.connect(m2m_changed_state_permissions, sender=State.permissions.through)
        pre_save.connect(disable_services_on_inactive, sender=User)
        m2m_changed.connect(state_member_corporations_changed, sender=State.member_corporations.through)
        m2m_changed.connect(state_member_characters_changed, sender=State.member_characters.through)
        m2m_changed.connect(state_member_alliances_changed, sender=State.member_alliances.through)
        post_save.connect(state_saved, sender=State) 
Example #27
Source File: apps.py    From Kiwi with GNU General Public License v2.0 5 votes vote down vote up
def ready(self):
        from django.db.models.signals import post_save, pre_delete, pre_save
        from .models import TestCase
        from tcms import signals

        pre_save.connect(signals.pre_save_clean, TestCase)
        post_save.connect(signals.handle_emails_post_case_save, TestCase)
        pre_delete.connect(signals.handle_emails_pre_case_delete, TestCase)
        pre_delete.connect(signals.handle_comments_pre_delete, TestCase) 
Example #28
Source File: apps.py    From openwisp-radius with GNU General Public License v3.0 5 votes vote down vote up
def connect_signals(self):
        OrganizationUser = swapper.load_model('openwisp_users', 'OrganizationUser')
        Organization = swapper.load_model('openwisp_users', 'Organization')
        User = get_user_model()

        post_save.connect(
            create_default_groups_handler,
            sender=Organization,
            dispatch_uid='create_default_groups',
        )
        post_save.connect(
            update_user_related_records,
            sender=User,
            dispatch_uid='update_user_related_records',
        )
        post_save.connect(
            set_default_group_handler,
            sender=OrganizationUser,
            dispatch_uid='set_default_group',
        )
        pre_save.connect(
            organization_pre_save,
            sender=Organization,
            dispatch_uid='openwisp_radius_org_pre_save',
        )
        post_save.connect(
            organization_post_save,
            sender=Organization,
            dispatch_uid='openwisp_radius_org_post_save',
        ) 
Example #29
Source File: signal.py    From mercure with GNU General Public License v3.0 5 votes vote down vote up
def test_add_campaign_report_item(self):
        def handler(context, **kwarg):
            context['tabs_layout']['Test'] = []

        make_campaign_report.connect(handler)

        # test
        content = self.get()
        self.assertIn('<a href="#test" aria-controls="test" role="tab" '
                      'data-toggle="tab">Test</a>', content)
        self.assertIn('id="test"', content)

        # clean
        self.assertTrue(make_campaign_report.disconnect(handler)) 
Example #30
Source File: apps.py    From Kiwi with GNU General Public License v2.0 5 votes vote down vote up
def ready(self):
        from django.db.models.signals import post_save, pre_save
        from .models import TestPlan
        from tcms import signals

        pre_save.connect(signals.pre_save_clean, TestPlan)
        post_save.connect(signals.handle_emails_post_plan_save, TestPlan)