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

The following are 10 code examples of django.db.models.signals.pre_delete(). 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: receivers.py    From pinax-documents with MIT License 5 votes vote down vote up
def ensure_userstorage(sender, **kwargs):
    if kwargs["created"]:
        user = kwargs["instance"]
        UserStorage.objects.create(user=user, bytes_total=(1024 * 1024 * 50))


# Receive the pre_delete signal and delete the file associated with the model instance. 
Example #2
Source File: builder.py    From resolwe with Apache License 2.0 5 votes vote down vote up
def connect(self, index):
        """Connect signals needed for dependency updates.

        Pre- and post-delete signals have to be handled separately, as:

          * in the pre-delete signal we have the information which
            objects to rebuild, but affected relations are still
            presented, so rebuild would reflect in the wrong (outdated)
            indices
          * in the post-delete signal indices can be rebuild corectly,
            but there is no information which objects to rebuild, as
            affected relations were already deleted

        To bypass this, list of objects should be stored in the
        pre-delete signal indexing should be triggered in the
        post-delete signal.
        """
        self.index = index

        signal = ElasticSignal(self, "process", pass_kwargs=True)
        signal.connect(post_save, sender=self.model)
        signal.connect(pre_delete, sender=self.model)

        pre_delete_signal = ElasticSignal(self, "process_predelete", pass_kwargs=True)
        pre_delete_signal.connect(pre_delete, sender=self.model)

        post_delete_signal = ElasticSignal(self, "process_delete", pass_kwargs=True)
        post_delete_signal.connect(post_delete, sender=self.model)

        return [signal, pre_delete_signal, post_delete_signal] 
Example #3
Source File: models.py    From waliki with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_absolute_url(self):
        return reverse('waliki_attachment_file', args=(self.page.slug, text_type(self)))


# @receiver(pre_delete, sender=Attachment)
# def attachment_delete(sender, instance, **kwargs):
#    try:
#        # instance.file.delete(False)
#        pass
#    except SuspiciousFileOperation:
#        pass 
Example #4
Source File: signals.py    From fermentrack with MIT License 5 votes vote down vote up
def handle_TiltTempCalibrationPoint_post_save(sender, **kwargs):
    """
    Trigger anything that should happen on update of TiltTempCalibrationPoint
    """

    calibration_point = kwargs.get('instance')
    try:
        calibration_point.sensor.set_redis_reload_flag()
    except:
        pass

# TODO - Add a pre_delete signal to trigger cessation of the relevant tilt_manager process 
Example #5
Source File: models.py    From InvenTree with MIT License 5 votes vote down vote up
def before_delete_stock_item(sender, instance, using, **kwargs):
    """ Receives pre_delete signal from StockItem object.

    Before a StockItem is deleted, ensure that each child object is updated,
    to point to the new parent item.
    """

    # Update each StockItem parent field
    for child in instance.children.all():
        child.parent = instance.parent
        child.save()

    # Rebuild the MPTT tree
    StockItem.objects.rebuild() 
Example #6
Source File: models.py    From InvenTree with MIT License 5 votes vote down vote up
def before_delete_tree_item(sender, instance, using, **kwargs):
    """ Receives pre_delete signal from InvenTreeTree object.

    Before an item is deleted, update each child object to point to the parent of the object being deleted.
    """

    # Update each tree item below this one
    for child in instance.children.all():
        child.parent = instance.parent
        child.save() 
Example #7
Source File: signals.py    From allianceauth with GNU General Public License v2.0 5 votes vote down vote up
def pre_delete_user(sender, instance, *args, **kwargs):
    logger.debug("Received pre_delete from %s" % instance)
    disable_user(instance) 
Example #8
Source File: models.py    From figures with MIT License 4 votes vote down vote up
def clean(self):
        if self.course_user_group.group_type != CourseUserGroup.COHORT:
            raise ValidationError("CohortMembership cannot be used with CourseGroup types other than COHORT")
        if self.course_user_group.course_id != self.course_id:
            raise ValidationError("Non-matching course_ids provided")

    # def save(self, *args, **kwargs):
    #     self.full_clean(validate_unique=False)

    #     # Avoid infinite recursion if creating from get_or_create() call below.
    #     # This block also allows middleware to use CohortMembership.get_or_create without worrying about outer_atomic
    #     if 'force_insert' in kwargs and kwargs['force_insert'] is True:
    #         with transaction.atomic():
    #             self.course_user_group.users.add(self.user)
    #             super(CohortMembership, self).save(*args, **kwargs)
    #         return

    #     # This block will transactionally commit updates to CohortMembership and underlying course_user_groups.
    #     # Note the use of outer_atomic, which guarantees that operations are committed to the database on block exit.
    #     # If called from a view method, that method must be marked with @transaction.non_atomic_requests.
    #     with outer_atomic(read_committed=True):

    #         saved_membership, created = CohortMembership.objects.select_for_update().get_or_create(
    #             user__id=self.user.id,
    #             course_id=self.course_id,
    #             defaults={
    #                 'course_user_group': self.course_user_group,
    #                 'user': self.user
    #             }
    #         )

    #         # If the membership was newly created, all the validation and course_user_group logic was settled
    #         # with a call to self.save(force_insert=True), which gets handled above.
    #         if created:
    #             return

    #         if saved_membership.course_user_group == self.course_user_group:
    #             raise ValueError("User {user_name} already present in cohort {cohort_name}".format(
    #                 user_name=self.user.username,
    #                 cohort_name=self.course_user_group.name
    #             ))
    #         self.previous_cohort = saved_membership.course_user_group
    #         self.previous_cohort_name = saved_membership.course_user_group.name
    #         self.previous_cohort_id = saved_membership.course_user_group.id
    #         self.previous_cohort.users.remove(self.user)

    #         saved_membership.course_user_group = self.course_user_group
    #         self.course_user_group.users.add(self.user)

    #         super(CohortMembership, saved_membership).save(update_fields=['course_user_group'])


# Needs to exist outside class definition in order to use 'sender=CohortMembership'
# @receiver(pre_delete, sender=CohortMembership)
# def remove_user_from_cohort(sender, instance, **kwargs):  # pylint: disable=unused-argument
#     """
#     Ensures that when a CohortMemebrship is deleted, the underlying CourseUserGroup
#     has its users list updated to reflect the change as well.
#     """
#     instance.course_user_group.users.remove(instance.user)
#     instance.course_user_group.save() 
Example #9
Source File: builder.py    From resolwe with Apache License 2.0 4 votes vote down vote up
def connect(self, index):
        """Connect signals needed for dependency updates."""
        # Determine which model is the target model as either side of the relation
        # may be passed as `field`.
        if index.object_type == self.field.rel.model:
            self.model = self.field.rel.related_model
            self.accessor = self.field.rel.field.attname
        else:
            self.model = self.field.rel.model
            if self.field.rel.symmetrical:
                # Symmetrical m2m relation on self has no reverse accessor.
                raise NotImplementedError(
                    "Dependencies on symmetrical M2M relations are not supported due "
                    "to strange handling of the m2m_changed signal which only makes "
                    "half of the relation visible during signal execution. For now you "
                    "need to use symmetrical=False on the M2M field definition."
                )
            else:
                self.accessor = self.field.rel.get_accessor_name()

        # Connect signals.
        signals = super().connect(index)

        m2m_signal = ElasticSignal(self, "process_m2m", pass_kwargs=True)
        m2m_signal.connect(m2m_changed, sender=self.field.through)
        signals.append(m2m_signal)

        # If the relation has a custom through model, we need to subscribe to it.
        if not self.field.rel.through._meta.auto_created:
            signal = ElasticSignal(self, "process_m2m_through_save", pass_kwargs=True)
            signal.connect(post_save, sender=self.field.rel.through)
            signals.append(signal)

            signal = ElasticSignal(
                self, "process_m2m_through_pre_delete", pass_kwargs=True
            )
            signal.connect(pre_delete, sender=self.field.rel.through)
            signals.append(signal)

            signal = ElasticSignal(
                self, "process_m2m_through_post_delete", pass_kwargs=True
            )
            signal.connect(post_delete, sender=self.field.rel.through)
            signals.append(signal)

        return signals 
Example #10
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
            )