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

The following are 25 code examples of django.db.models.signals.pre_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.pre_save , or try the search function .
Example #1
Source File: middleware.py    From django-actions-logger with MIT License 6 votes vote down vote up
def process_request(self, request):
        """
        Gets the current user from the request and prepares and connects a signal receiver with the user already
        attached to it.
        """
        # Initialize thread local storage
        threadlocal.actionslog = {
            'signal_duid': (self.__class__, time.time()),
            'remote_ip': request.META.get('REMOTE_ADDR'),
        }

        # In case of proxy, set 'original' address
        if request.META.get('HTTP_X_FORWARDED_FOR'):
            threadlocal.actionslog['remote_ip'] = request.META.get('HTTP_X_FORWARDED_FOR').split(',')[0]

        # Connect signal for automatic logging
        if hasattr(request, 'user') and hasattr(request.user, 'is_authenticated') and request.user.is_authenticated():
            set_user = curry(self.set_user, request.user)
            pre_save.connect(set_user, sender=LogAction, dispatch_uid=threadlocal.actionslog['signal_duid'], weak=False) 
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: 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 #5
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 #6
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 #7
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 #8
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 #9
Source File: apps.py    From substra-backend with Apache License 2.0 6 votes vote down vote up
def ready(self):
        from .signals.datasample.pre_save import data_sample_pre_save

        from .signals.algo.post_delete import algo_post_delete
        from .signals.objective.post_delete import objective_post_delete
        from .signals.datasample.post_delete import data_sample_post_delete
        from .signals.datamanager.post_delete import datamanager_post_delete
        from .signals.model.post_delete import model_post_delete

        # registering signals with the model's string label
        from substrapp.models import Algo, Objective, DataSample, DataManager, Model

        pre_save.connect(data_sample_pre_save, sender=DataSample)

        post_delete.connect(algo_post_delete, sender=Algo)
        post_delete.connect(objective_post_delete, sender=Objective)
        post_delete.connect(data_sample_post_delete, sender=DataSample)
        post_delete.connect(datamanager_post_delete, sender=DataManager)
        post_delete.connect(model_post_delete, sender=Model) 
Example #10
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 #11
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 #12
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 #13
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 #14
Source File: apps.py    From django-usersettings2 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def ready(self):
        from .models import clear_usersettings_cache
        from .shortcuts import get_usersettings_model

        usersettings_model = get_usersettings_model()
        pre_save.connect(clear_usersettings_cache, sender=usersettings_model)
        pre_delete.connect(clear_usersettings_cache, sender=usersettings_model) 
Example #15
Source File: tests.py    From django-useraudit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def register_pre_save_on_AUTH_USER_MODER_change(sender, setting, value, enter, **kwargs):
    if setting == "AUTH_USER_MODEL" and value != USER_MODEL:
        if enter:
            pre_save.connect(useraudit.password_expiry.user_pre_save, sender=value)
        else:
            pre_save.disconnect(useraudit.password_expiry.user_pre_save, sender=value) 
Example #16
Source File: tests.py    From django-useraudit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_signal(self):
        def handler(sender, user=None, **kwargs):
            self.handler_called = True
            self.assertEquals(sender, type(self.user))
            self.assertEquals(user, self.user)
        login_failure_limit_reached.connect(handler)

        self.handler_called = False

        _ = authenticate(username=self.username, password="INCORRECT")
        _ = authenticate(username=self.username, password="INCORRECT")

        login_failure_limit_reached.disconnect(handler)

        self.assertTrue(self.handler_called) 
Example #17
Source File: receivers.py    From wagtail-personalisation with MIT License 5 votes vote down vote up
def register():
    pre_save.connect(check_status_change, sender=Segment) 
Example #18
Source File: apps.py    From Inboxen with GNU Affero General Public License v3.0 5 votes vote down vote up
def ready(self):
        BlogPost = self.get_model("BlogPost")
        pre_save.connect(signals.published_checker, sender=BlogPost, dispatch_uid="blog_date_draft_checker") 
Example #19
Source File: signal_handlers.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def register_signal_handlers():
    Image = get_image_model()
    Rendition = Image.get_rendition_model()

    pre_save.connect(pre_save_image_feature_detection, sender=Image)
    post_delete.connect(post_delete_file_cleanup, sender=Image)
    post_delete.connect(post_delete_file_cleanup, sender=Rendition)
    post_delete.connect(post_delete_purge_rendition_cache, sender=Rendition) 
Example #20
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) 
Example #21
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, pre_delete
        from .models import TestExecution, TestRun
        from tcms import signals

        post_save.connect(signals.handle_emails_post_run_save, sender=TestRun)
        pre_save.connect(signals.pre_save_clean, sender=TestRun)
        pre_delete.connect(signals.handle_comments_pre_delete, TestExecution) 
Example #22
Source File: utils.py    From product-definition-center with MIT License 5 votes vote down vote up
def connect_app_models_pre_save_signal(app, models=None):
    for model in models or app.get_models():
        pre_save.connect(validate_model, sender=model, dispatch_uid=str(model)) 
Example #23
Source File: apps.py    From substra-backend with Apache License 2.0 5 votes vote down vote up
def ready(self):
        from node.models import IncomingNode
        from node.signals.node.pre_save import node_pre_save

        pre_save.connect(node_pre_save, sender=IncomingNode) 
Example #24
Source File: test_signals.py    From django-linguist with MIT License 5 votes vote down vote up
def pre_post_save_wrapper(self):
        self.pre_save_called = False
        self.post_save_called = False

        self.bar

        def pre_save_handler(sender, instance, **kwargs):
            # Assert that a pre_save handler gets the proper information on which fields have changed
            # (hence the translations have not yet been saved to the db).

            self.pre_save_called = True

            field_fr = instance._linguist_translations["title"].get("fr", None)
            field_en = instance._linguist_translations["title"].get("en", None)

            assert field_fr.has_changed
            assert not field_en.has_changed

        pre_save.connect(pre_save_handler, sender=BarModel)

        def post_save_handler(sender, instance, **kwargs):
            # Assert that a post_save handler that refreshes the model gets the saved translations
            # (hence the translations have been saved to the db).

            self.post_save_called = True

            title_fr = instance.title_fr
            title_en = instance.title_en

            instance = BarModel.objects.get(pk=instance.pk)

            assert instance.title_fr == title_fr
            assert instance.title_en == title_en

        post_save.connect(post_save_handler, sender=BarModel)

        yield

        pre_save.disconnect(pre_save_handler, sender=BarModel)
        post_save.disconnect(post_save_handler, sender=BarModel) 
Example #25
Source File: signals.py    From site with MIT License 5 votes vote down vote up
def __init__(self):
        post_save.connect(self.user_model_updated, sender=DiscordUser)

        post_delete.connect(self.mapping_model_deleted, sender=RoleMapping)
        pre_save.connect(self.mapping_model_updated, sender=RoleMapping)

        pre_social_login.connect(self.social_account_updated)
        social_account_added.connect(self.social_account_updated)
        social_account_updated.connect(self.social_account_updated)
        social_account_removed.connect(self.social_account_removed)

        user_logged_in.connect(self.user_logged_in)