我们从Python开源项目中,提取了以下5个代码示例,用于说明如何使用django.db.models.signals.pre_save()。
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
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)
def pre_save(self, instance, *args, **kwargs): from django.utils.text import slugify if not instance.slug: instance.slug = slugify(self.slug_source)
def update_domain_serial_when_interface_deleted(sender, instance, **kwargs): if instance.domain is not None: domain = instance.domain domain.domain_serial += 1 domain.save() if instance.ip4address is not None: subnet = instance.ip4address.subnet subnet.domain_serial += 1 subnet.save() # @receiver(pre_save, sender=Domain) # def update_domain_serial_when_domain_is_saved(sender, instance, **kwargs): # instance.domain_serial = format_domain_serial_and_add_one(instance.domain_serial)
def update_zipfile(sender, instance, **kwargs): """ Delete zip file on pre_save. This is needed in case of updation of zip file, where the older file should be deleted from the location""" if instance.pk: details = SponsorProjectDetailsSubFields.objects.get(pk=instance.pk) if details.zip_file and details.zip_file.url != instance.zip_file.url: storage, path = details.zip_file.storage, details.zip_file.path storage.delete(path)