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

The following are 17 code examples of django.db.models.signals.post_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: models.py    From clist with Apache License 2.0 5 votes vote down vote up
def count_resource_accounts(signal, instance, **kwargs):
    if signal is post_delete:
        instance.resource.n_accounts -= 1
        instance.resource.save()
    elif signal is post_save and kwargs['created']:
        instance.resource.n_accounts += 1
        instance.resource.save() 
Example #2
Source File: bmc.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def pre_delete_bmc_clean_orphaned_ip(sender, instance, **kwargs):
    """Stash the soon-to-be-deleted BMC's ip_address for use in post_delete."""
    instance.__previous_ip_address = instance.ip_address 
Example #3
Source File: bootresourcefiles.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def delete_large_file(sender, instance, **kwargs):
    """Call delete on the LargeFile, now that the relation has been removed.
    If this was the only resource file referencing this LargeFile then it will
    be delete.

    This is done using the `post_delete` signal because only then has the
    relation been removed.
    """
    try:
        largefile = instance.largefile
    except LargeFile.DoesNotExist:
        pass  # Nothing to do.
    else:
        if largefile is not None:
            largefile.delete() 
Example #4
Source File: largefiles.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def delete_large_object(sender, instance, **kwargs):
    """Delete the large object when the `LargeFile` is deleted.

    This is done using the `post_delete` signal instead of overriding delete
    on `LargeFile`, so it works correctly for both the model and `QuerySet`.
    """
    if instance.content is not None:
        post_commit_do(delete_large_object_content_later, instance.content) 
Example #5
Source File: unseed_db.py    From micromasters with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def unseed_db():
    """
    Deletes all seed data from the database
    """
    fake_program_ids = (
        Program.objects
        .filter(description__startswith=FAKE_PROGRAM_DESC_PREFIX)
        .values_list('id', flat=True)
    )
    fake_user_ids = (
        User.objects
        .filter(username__startswith=FAKE_USER_USERNAME_PREFIX)
        .values_list('id', flat=True)
    )
    fake_tier_ids = (
        TierProgram.objects
        .filter(program__id__in=fake_program_ids)
        .values_list('tier__id', flat=True)
    )
    fake_final_grade_ids = (
        FinalGrade.objects
        .filter(course_run__course__program__id__in=fake_program_ids)
        .values_list('id', flat=True)
    )
    financial_aid_ids = (
        FinancialAid.objects
        .filter(Q(user_id__in=fake_user_ids) | Q(tier_program__program__id__in=fake_program_ids))
        .values_list('id', flat=True)
    )
    fin_aid_audit_models = [FinancialAidAudit, FinancialAidEmailAudit]
    with mute_signals(post_delete):
        with remove_delete_protection(*fin_aid_audit_models):
            for audit_model in fin_aid_audit_models:
                audit_model.objects.filter(financial_aid__id__in=financial_aid_ids).delete()
        for model_cls in [CachedEnrollment, CachedCertificate, CachedCurrentGrade]:
            model_cls.objects.filter(course_run__course__program__id__in=fake_program_ids).delete()
        Tier.objects.filter(id__in=fake_tier_ids).delete()
        FinalGrade.objects.filter(id__in=fake_final_grade_ids).delete()
        Program.objects.filter(id__in=fake_program_ids).delete()
        User.objects.filter(id__in=fake_user_ids).delete() 
Example #6
Source File: models.py    From django-drf-filepond with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def delete_temp_upload_file(sender, instance, **kwargs):
    # Check that the file parameter for the instance is not None
    # and that the file exists and is not a directory! Then we can delete it
    LOG.debug('*** post_delete signal handler called. Deleting file.')
    if instance.file:
        if (os.path.exists(instance.file.path) and
                os.path.isfile(instance.file.path)):
            os.remove(instance.file.path)

    if local_settings.DELETE_UPLOAD_TMP_DIRS:
        file_dir = os.path.join(storage.location, instance.upload_id)
        if(os.path.exists(file_dir) and os.path.isdir(file_dir)):
            os.rmdir(file_dir)
            LOG.debug('*** post_delete signal handler called. Deleting temp '
                      'dir that contained file.') 
Example #7
Source File: models.py    From django-drf-filepond with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_absolute_file_path(self):
        fsp = local_settings.FILE_STORE_PATH
        if not fsp:
            fsp = ''
        return os.path.join(fsp, self.file.name)


# When a TemporaryUpload record is deleted, we need to delete the
# corresponding file from the filesystem by catching the post_delete signal. 
Example #8
Source File: models.py    From clist with Apache License 2.0 5 votes vote down vote up
def count_account_contests(signal, instance, **kwargs):
    if instance.addition.get('_no_update_n_contests'):
        return

    if signal is post_delete:
        instance.account.n_contests -= 1
        instance.account.save()
    elif signal is post_save and kwargs['created']:
        instance.account.n_contests += 1

        if not instance.account.last_activity or instance.account.last_activity < instance.contest.start_time:
            instance.account.last_activity = instance.contest.start_time

        instance.account.save() 
Example #9
Source File: apps.py    From openwisp-users with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def connect_receivers(self):
        OrganizationUser = load_model('openwisp_users', 'OrganizationUser')
        OrganizationOwner = load_model('openwisp_users', 'OrganizationOwner')
        signal_tuples = [(post_save, 'post_save'), (post_delete, 'post_delete')]

        for model in [OrganizationUser, OrganizationOwner]:
            for signal, name in signal_tuples:
                signal.connect(
                    self.update_organizations_dict,
                    sender=model,
                    dispatch_uid='{}_{}_update_organizations_dict'.format(
                        name, model.__name__
                    ),
                ) 
Example #10
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 #11
Source File: pdns_change_tracker.py    From desec-stack with MIT License 5 votes vote down vote up
def _manage_signals(self, method):
        if method not in ['connect', 'disconnect']:
            raise ValueError()
        getattr(post_save, method)(self._on_rr_post_save, sender=RR, dispatch_uid=self.__module__)
        getattr(post_delete, method)(self._on_rr_post_delete, sender=RR, dispatch_uid=self.__module__)
        getattr(post_save, method)(self._on_rr_set_post_save, sender=RRset, dispatch_uid=self.__module__)
        getattr(post_delete, method)(self._on_rr_set_post_delete, sender=RRset, dispatch_uid=self.__module__)
        getattr(post_save, method)(self._on_domain_post_save, sender=Domain, dispatch_uid=self.__module__)
        getattr(post_delete, method)(self._on_domain_post_delete, sender=Domain, dispatch_uid=self.__module__) 
Example #12
Source File: builder.py    From resolwe with Apache License 2.0 5 votes vote down vote up
def _connect_signal(self, index):
        """Create signals for building indexes."""
        post_save_signal = ElasticSignal(index, "build")
        post_save_signal.connect(post_save, sender=index.object_type)
        self.signals.append(post_save_signal)

        post_delete_signal = ElasticSignal(index, "remove_object")
        post_delete_signal.connect(post_delete, sender=index.object_type)
        self.signals.append(post_delete_signal)

        # Connect signals for all dependencies.
        for dependency in index.get_dependencies():
            # Automatically convert m2m fields to dependencies.
            if isinstance(dependency, (models.ManyToManyField, ManyToManyDescriptor)):
                dependency = ManyToManyDependency(dependency)
            elif isinstance(dependency, ReverseManyToOneDescriptor):
                dependency = ReverseManyToOneDependency(dependency)
            elif isinstance(dependency, ForwardManyToOneDescriptor):
                dependency = ForwardManyToOneDependency(dependency)
            elif not isinstance(dependency, Dependency):
                raise TypeError(
                    "Unsupported dependency type: {}".format(repr(dependency))
                )

            signal = dependency.connect(index)
            self.signals.extend(signal) 
Example #13
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 #14
Source File: signals.py    From tracker_project with MIT License 5 votes vote down vote up
def post_delete(sender, **kwargs):
    send_notification(dict(
        type='post_delete',
        feature=kwargs['instance'].geojson_feature
    )) 
Example #15
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() 
Example #16
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 #17
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