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

The following are 23 code examples of django.db.models.signals.pre_save(). 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 , or try the search function .
Example #1
Source File: password_expiry.py    From django-useraudit with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def user_pre_save(sender, instance=None, raw=False, **kwargs):
    user = instance
    attrs = ExpirySettings.get()
    # We're saving the password change date only for existing users
    # Users just created should be taken care of by auto_now_add.
    # This way we can assume that a User profile object already exists
    # for the user. This is essential, because password change detection
    # can happen only in pre_save, in post_save it is too late.
    is_new_user = user.pk is None
    if is_new_user or raw:
        return
    if attrs.date_changed:
        update_date_changed(user, attrs.date_changed)

    # User has been re-activated. Ensure the last_login is set to None so
    # that the user isn't inactivated on next login by the AccountExpiryBackend
    current_user = sender.objects.get(pk=user.pk)
    if not current_user.is_active and user.is_active:
        user.last_login = None 
Example #2
Source File: models.py    From clist with Apache License 2.0 6 votes vote down vote up
def update_account_url(signal, instance, **kwargs):

    def default_url():
        args = [instance.key, instance.resource.host]
        return reverse('coder:account', args=args)

    if signal is pre_save:
        if instance.url:
            return
        instance.url = default_url()
    elif signal is m2m_changed:
        if not kwargs.get('action').startswith('post_'):
            return
        url = None
        for coder in instance.coders.iterator():
            if url is not None:
                url = None
                break
            url = reverse('coder:profile', args=[coder.username]) + f'?search=resource:{instance.resource.host}'
        instance.url = url
        instance.save() 
Example #3
Source File: signals.py    From edx-proctoring with GNU Affero General Public License v3.0 6 votes vote down vote up
def save_exam_on_backend(sender, instance, **kwargs):  # pylint: disable=unused-argument
    """
    Save the exam to the backend provider when our model changes.
    It also combines the review policy into the exam when saving to the backend
    """
    if sender == models.ProctoredExam:
        exam_obj = instance
        review_policy = models.ProctoredExamReviewPolicy.get_review_policy_for_exam(instance.id)
    else:
        exam_obj = instance.proctored_exam
        review_policy = instance
    if exam_obj.is_proctored:
        from edx_proctoring.serializers import ProctoredExamJSONSafeSerializer
        exam = ProctoredExamJSONSafeSerializer(exam_obj).data
        if review_policy:
            exam['rule_summary'] = review_policy.review_policy
        backend = get_backend_provider(exam)
        external_id = backend.on_exam_saved(exam)
        if external_id and external_id != exam_obj.external_id:
            exam_obj.external_id = external_id
            exam_obj.save()


# Hook up the pre_save signal to record creations in the ProctoredExamReviewPolicyHistory table. 
Example #4
Source File: signals.py    From allianceauth with GNU General Public License v2.0 6 votes vote down vote up
def pre_save_config(sender, instance, *args, **kwargs):
    """
    Checks if enable was toggled on group config and
    deletes groups if necessary.
    """
    logger.debug("Received pre_save from {}".format(instance))
    if not instance.pk:
        # new model being created
        return
    try:
        old_instance = AutogroupsConfig.objects.get(pk=instance.pk)

        # Check if enable was toggled, delete groups?
        if old_instance.alliance_groups is True and instance.alliance_groups is False:
            instance.delete_alliance_managed_groups()

        if old_instance.corp_groups is True and instance.corp_groups is False:
            instance.delete_corp_managed_groups()
    except AutogroupsConfig.DoesNotExist:
        pass 
Example #5
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_decorators(self):
        data = []

        @receiver(signals.pre_save, weak=False)
        def decorated_handler(signal, sender, instance, **kwargs):
            data.append(instance)

        @receiver(signals.pre_save, sender=Car, weak=False)
        def decorated_handler_with_sender_arg(signal, sender, instance, **kwargs):
            data.append(instance)

        try:
            c1 = Car.objects.create(make="Volkswagen", model="Passat")
            self.assertEqual(data, [c1, c1])
        finally:
            signals.pre_save.disconnect(decorated_handler)
            signals.pre_save.disconnect(decorated_handler_with_sender_arg, sender=Car) 
Example #6
Source File: test_invoice.py    From silver with Apache License 2.0 6 votes vote down vote up
def test_get_invoice(authenticated_api_client, settings, issued_invoice):
    invoice = issued_invoice
    customer = issued_invoice.customer

    issued_invoice.generate_pdf()

    with mute_signals(pre_save):
        [
            TransactionFactory.create(
                state=state, invoice=issued_invoice,
                payment_method=PaymentMethodFactory(customer=customer)
            )
            for state in Transaction.States.as_list()
            if state not in [Transaction.States.Canceled,
                             Transaction.States.Refunded,
                             Transaction.States.Failed]
        ]

    url = reverse('invoice-detail', kwargs={'pk': invoice.pk})

    response = authenticated_api_client.get(url, format='json')

    assert response.status_code == status.HTTP_200_OK, response.data
    invoice_definition.check_response(invoice, response_data=response.data) 
Example #7
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_decorators(self):
        data = []

        @receiver(signals.pre_save, weak=False)
        def decorated_handler(signal, sender, instance, **kwargs):
            data.append(instance)

        @receiver(signals.pre_save, sender=Car, weak=False)
        def decorated_handler_with_sender_arg(signal, sender, instance, **kwargs):
            data.append(instance)

        try:
            c1 = Car.objects.create(make="Volkswagen", model="Passat")
            self.assertEqual(data, [c1, c1])
        finally:
            signals.pre_save.disconnect(decorated_handler)
            signals.pre_save.disconnect(decorated_handler_with_sender_arg, sender=Car) 
Example #8
Source File: signals.py    From allianceauth with GNU General Public License v2.0 5 votes vote down vote up
def disable_services_on_inactive(sender, instance, *args, **kwargs):
    logger.debug("Received pre_save from %s" % instance)
    # check if user is being marked active/inactive
    if not instance.pk:
        # new model being created
        return
    try:
        old_instance = User.objects.get(pk=instance.pk)
        if old_instance.is_active and not instance.is_active:
            logger.info("Disabling services for inactivation of user %s" % instance)
            disable_user(instance)
    except User.DoesNotExist:
        pass 
Example #9
Source File: registry.py    From django-actions-logger with MIT License 5 votes vote down vote up
def __init__(self, create=True, update=True, delete=True, custom=None):
        from actionslog.receivers import action_log_create, action_log_update, action_log_delete

        self._registry = {}
        self._signals = {}

        if create:
            self._signals[post_save] = action_log_create
        if update:
            self._signals[pre_save] = action_log_update
        if delete:
            self._signals[post_delete] = action_log_delete

        if custom is not None:
            self._signals.update(custom) 
Example #10
Source File: signals.py    From allianceauth with GNU General Public License v2.0 5 votes vote down vote up
def state_saved(sender, instance, *args, **kwargs):
    logger.debug('State {} saved. Re-evaluating membership.'.format(instance))
    trigger_state_check(instance)


# Is there a smarter way to intercept pre_save with a diff main_character or state? 
Example #11
Source File: nodes.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def post_init_store_previous_status(sender, instance, **kwargs):
    """Store the pre_save status of the instance."""
    instance.__previous_status = instance.status 
Example #12
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def setUp(self):
        # Save up the number of connected signals so that we can check at the
        # end that all the signals we register get properly unregistered (#9989)
        self.pre_signals = (
            len(signals.pre_save.receivers),
            len(signals.post_save.receivers),
            len(signals.pre_delete.receivers),
            len(signals.post_delete.receivers),
        ) 
Example #13
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        # All our signals got disconnected properly.
        post_signals = (
            len(signals.pre_save.receivers),
            len(signals.post_save.receivers),
            len(signals.pre_delete.receivers),
            len(signals.post_delete.receivers),
        )
        self.assertEqual(self.pre_signals, post_signals) 
Example #14
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def setUp(self):
        # Save up the number of connected signals so that we can check at the
        # end that all the signals we register get properly unregistered (#9989)
        self.pre_signals = (
            len(signals.pre_save.receivers),
            len(signals.post_save.receivers),
            len(signals.pre_delete.receivers),
            len(signals.post_delete.receivers),
        ) 
Example #15
Source File: signals.py    From TWLight with MIT License 5 votes vote down vote up
def set_partner_status(sender, **kwargs):
    """
    Whenever an application is approved (except for in BatchEditView)
    we do some calculations to see if we've run out of accounts. If 
    we have, we mark the partner as waitlisted if not, continue.
    """
    partner_pk = kwargs["partner_pk"]
    try:
        partner = Partner.objects.get(pk=partner_pk)
        partner.status = Partner.WAITLIST
        partner.save()
    except Partner.DoesNotExist:
        logger.info(
            "set_partner_status signal received, but"
            " partner {pk} does not exist - unable to set"
            " partner status".format(pk=partner_pk)
        )


# IMPORTANT: pre_save is not sent by Queryset.update(), so *none of this
# behavior will happen on if you update() an Application queryset*.
# That is sometimes okay, but it is not always okay.
# Errors caused by days_open not existing when expected to
# exist can show up in weird parts of the application (for example, template
# rendering failing when get_num_days_open returns None but its output is
# passed to a template filter that needs an integer). 
Example #16
Source File: signals.py    From edx-proctoring with GNU Affero General Public License v3.0 5 votes vote down vote up
def on_review_changed(sender, instance, signal, **kwargs):  # pylint: disable=unused-argument
    """
    Archiving all changes made to the Review.
    Will only archive on update/delete, and not on new entries created.
    """
    if signal is pre_save:
        if instance.id:
            # only for update cases
            instance = sender.objects.get(id=instance.id)
        else:
            # don't archive on create
            return
    models.archive_model(models.ProctoredExamSoftwareSecureReviewHistory, instance, id='review_id') 
Example #17
Source File: signals.py    From edx-proctoring with GNU Affero General Public License v3.0 5 votes vote down vote up
def on_attempt_changed(sender, instance, signal, **kwargs):  # pylint: disable=unused-argument
    """
    Archive the exam attempt whenever the attempt status is about to be
    modified. Make a new entry with the previous value of the status in the
    ProctoredExamStudentAttemptHistory table.
    """

    if signal is pre_save:
        if instance.id:
            # on an update case, get the original
            # and see if the status has changed, if so, then we need
            # to archive it
            original = sender.objects.get(id=instance.id)

            if original.status != instance.status:
                instance = original
            else:
                return
        else:
            return
    else:
        # remove the attempt on the backend
        # timed exams have no backend
        backend = get_backend_provider(name=instance.proctored_exam.backend)
        if backend:
            result = backend.remove_exam_attempt(instance.proctored_exam.external_id, instance.external_id)
            if not result:
                log.error(u'Failed to remove attempt %d from %s', instance.id, backend.verbose_name)
    models.archive_model(models.ProctoredExamStudentAttemptHistory, instance, id='attempt_id')


# Hook up the signals to record updates/deletions in the ProctoredExamSoftwareSecureReview table. 
Example #18
Source File: signals.py    From edx-proctoring with GNU Affero General Public License v3.0 5 votes vote down vote up
def on_allowance_changed(sender, instance, signal, **kwargs):  # pylint: disable=unused-argument
    """
    Archiving all changes made to the Student Allowance.
    Will only archive on update/delete, and not on new entries created.
    """

    if signal is pre_save:
        if instance.id:
            instance = sender.objects.get(id=instance.id)
        else:
            return
    models.archive_model(models.ProctoredExamStudentAllowanceHistory, instance, id='allowance_id') 
Example #19
Source File: signals.py    From edx-proctoring with GNU Affero General Public License v3.0 5 votes vote down vote up
def on_review_policy_changed(sender, instance, signal, **kwargs):  # pylint: disable=unused-argument
    """
    Archiving all changes made to the Review Policy.
    Will only archive on update/delete, and not on new entries created.
    """
    if signal is pre_save:
        if instance.id:
            instance = sender.objects.get(id=instance.id)
        else:
            return
    models.archive_model(models.ProctoredExamReviewPolicyHistory, instance, id='original_id')


# Hook up the post_save signal to record creations in the ProctoredExamStudentAllowanceHistory table. 
Example #20
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 4 votes vote down vote up
def test_save_and_delete_signals_with_m2m(self):
        data = []

        def pre_save_handler(signal, sender, instance, **kwargs):
            data.append('pre_save signal, %s' % instance)
            if kwargs.get('raw'):
                data.append('Is raw')

        def post_save_handler(signal, sender, instance, **kwargs):
            data.append('post_save signal, %s' % instance)
            if 'created' in kwargs:
                if kwargs['created']:
                    data.append('Is created')
                else:
                    data.append('Is updated')
            if kwargs.get('raw'):
                data.append('Is raw')

        def pre_delete_handler(signal, sender, instance, **kwargs):
            data.append('pre_delete signal, %s' % instance)
            data.append('instance.id is not None: %s' % (instance.id is not None))

        def post_delete_handler(signal, sender, instance, **kwargs):
            data.append('post_delete signal, %s' % instance)
            data.append('instance.id is not None: %s' % (instance.id is not None))

        signals.pre_save.connect(pre_save_handler, weak=False)
        signals.post_save.connect(post_save_handler, weak=False)
        signals.pre_delete.connect(pre_delete_handler, weak=False)
        signals.post_delete.connect(post_delete_handler, weak=False)
        try:
            a1 = Author.objects.create(name='Neal Stephenson')
            self.assertEqual(data, [
                "pre_save signal, Neal Stephenson",
                "post_save signal, Neal Stephenson",
                "Is created"
            ])
            data[:] = []

            b1 = Book.objects.create(name='Snow Crash')
            self.assertEqual(data, [
                "pre_save signal, Snow Crash",
                "post_save signal, Snow Crash",
                "Is created"
            ])
            data[:] = []

            # Assigning and removing to/from m2m shouldn't generate an m2m signal.
            b1.authors.set([a1])
            self.assertEqual(data, [])
            b1.authors.set([])
            self.assertEqual(data, [])
        finally:
            signals.pre_save.disconnect(pre_save_handler)
            signals.post_save.disconnect(post_save_handler)
            signals.pre_delete.disconnect(pre_delete_handler)
            signals.post_delete.disconnect(post_delete_handler) 
Example #21
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 4 votes vote down vote up
def test_save_and_delete_signals_with_m2m(self):
        data = []

        def pre_save_handler(signal, sender, instance, **kwargs):
            data.append('pre_save signal, %s' % instance)
            if kwargs.get('raw'):
                data.append('Is raw')

        def post_save_handler(signal, sender, instance, **kwargs):
            data.append('post_save signal, %s' % instance)
            if 'created' in kwargs:
                if kwargs['created']:
                    data.append('Is created')
                else:
                    data.append('Is updated')
            if kwargs.get('raw'):
                data.append('Is raw')

        def pre_delete_handler(signal, sender, instance, **kwargs):
            data.append('pre_delete signal, %s' % instance)
            data.append('instance.id is not None: %s' % (instance.id is not None))

        def post_delete_handler(signal, sender, instance, **kwargs):
            data.append('post_delete signal, %s' % instance)
            data.append('instance.id is not None: %s' % (instance.id is not None))

        signals.pre_save.connect(pre_save_handler, weak=False)
        signals.post_save.connect(post_save_handler, weak=False)
        signals.pre_delete.connect(pre_delete_handler, weak=False)
        signals.post_delete.connect(post_delete_handler, weak=False)
        try:
            a1 = Author.objects.create(name='Neal Stephenson')
            self.assertEqual(data, [
                "pre_save signal, Neal Stephenson",
                "post_save signal, Neal Stephenson",
                "Is created"
            ])
            data[:] = []

            b1 = Book.objects.create(name='Snow Crash')
            self.assertEqual(data, [
                "pre_save signal, Snow Crash",
                "post_save signal, Snow Crash",
                "Is created"
            ])
            data[:] = []

            # Assigning and removing to/from m2m shouldn't generate an m2m signal.
            b1.authors.set([a1])
            self.assertEqual(data, [])
            b1.authors.set([])
            self.assertEqual(data, [])
        finally:
            signals.pre_save.disconnect(pre_save_handler)
            signals.post_save.disconnect(post_save_handler)
            signals.pre_delete.disconnect(pre_delete_handler)
            signals.post_delete.disconnect(post_delete_handler) 
Example #22
Source File: services.py    From django-htk with MIT License 4 votes vote down vote up
def connect_receiver(self, model, path, depends_on):
        def change_receiver(instance, signame, update_fields=None, save=True, force=None, second_check=False, *args, **kwargs):
            source = '%s receiver %s, path %s, update_fields %s' % (signame, fmt(instance), path, update_fields)
            if '*' not in depends_on and update_fields is not None and not (set(update_fields) & depends_on):
                return
            if save:
                force = None
            for resolved_instance in resolve_instances(instance, path):
                old_resolved_instance = None
                if second_check:
                    old_resolved_instance = resolved_instance
                    resolved_instance = resolved_instance._meta.model.objects.get(pk=resolved_instance.pk)
                self.store_mp_or_async(resolved_instance, source=source, save=save, force=force, changed_only=second_check)
                if old_resolved_instance:
                    setattr(old_resolved_instance, self.field_name, getattr(resolved_instance, self.field_name))

            if second_check:
                return

            for dependent_mp, dependent_path in self.dependent_mps:
                for resolved_instance in resolve_instances(instance, dependent_path):
                    dependent_mp.store_mp_or_async(resolved_instance, source=source)

        if model == self.cls and not self.eventually_consistent:
            priority_connect(
                signals.pre_save,
                partial(change_receiver, signame='pre_save', save=False),
                sender=model
            )
            if self.dbl_check_on_post_save:
                priority_connect(
                    signals.post_save,
                    partial(change_receiver, signame='post_save(2)', second_check=True),
                    sender=model,
                )
        else:
            priority_connect(
                signals.post_save,
                partial(change_receiver, signame='post_save'),
                sender=model
            )

        if model != self.cls:
            priority_connect(
                signals.post_delete,
                partial(change_receiver, signame='post_delete'),
                sender=model
            )
        else:
            priority_connect(
                signals.pre_delete,
                mark_pending_delete,
                sender=model
            )
            priority_connect(
                signals.post_delete,
                unmark_pending_delete,
                sender=model
            ) 
Example #23
Source File: apps.py    From pasportaservo with GNU Affero General Public License v3.0 4 votes vote down vote up
def make_visibility_receivers(for_sender, field_name, visibility_model):
    """
    Creates signal receivers for watched models. Must be defered because models
    do not become available until after the app is readied.
    - for_sender: the watched model.
    - field_name: the visibility field within the model.
    - visibility_model: the specific model according to the type of data.
    """
    uid = '{}--{}'.format(for_sender, field_name)
    foreign_key = '{}_id'.format(field_name)

    @receiver(signals.pre_save, sender=for_sender, weak=False, dispatch_uid=uid)
    def hosting_model_pre_save(sender, **kwargs):
        """
        Creates a new specific visibility object directly in database,
        if one does not yet exist.
        """
        if kwargs['raw'] or getattr(kwargs['instance'], foreign_key) is not None:
            return
        setattr(kwargs['instance'], field_name, visibility_model.prep())

    @receiver(signals.post_save, sender=for_sender, weak=False, dispatch_uid=uid)
    def hosting_model_post_save(sender, **kwargs):
        """
        Links the specific visibility object to the newly created model
        instance. If the instance already has linkage, nothing happens.
        """
        if kwargs['raw']:
            return
        instance = kwargs['instance']
        visibility_model.objects.filter(
            id=getattr(instance, foreign_key), model_id__isnull=True,
        ).update(model_id=instance.pk)

    @receiver(signals.post_delete, sender=for_sender, weak=False, dispatch_uid=uid)
    def hosting_model_post_delete(sender, **kwargs):
        """
        Deletes the visibility object linked to the watched model instance.
        """
        visibility_model.objects.filter(
            id=getattr(kwargs['instance'], foreign_key),
        ).delete()