A pre_save signal handler which attaches an attribute to the model instance
    containing all uncommitted ``FileField``s, which can then be used by the
    :func:`signal_committed_filefields` post_save handler.
356472
def find_uncommitted_filefields(sender, instance, **kwargs):
    
    uncommitted = instance._uncommitted_filefields = []

    fields = sender._meta.fields
    if kwargs.get('update_fields', None):
        update_fields = set(kwargs['update_fields'])
        fields = update_fields.intersection(fields)
    for field in fields:
        if isinstance(field, FileField):
            fieldfile = getattr(instance, field.name)
            if fieldfile and not fieldfile._committed:
                uncommitted.append(field.name)
1016453
def get_unbound_form(self):
        
        form_kwargs = self.get_form_kwargs()
        # @@@ remove fields that would cause the form to be bound
        # when instantiated
        bound_fields = ["data", "files"]
        for field in bound_fields:
            form_kwargs.pop(field, None)
        return self.get_form_class()(**form_kwargs)
255652
def user_post_save_handler(**kwargs):
    """"""
    if kwargs.get('created'):
        total = get_user_model().objects.all().count()
        data = [{
            'measurement': 'django_auth_user_create',
            'tags': {'host': settings.INFLUXDB_TAGS_HOST, },
            'fields': {'value': 1, },
            'time': timezone.now().isoformat(),
        }]
        write_points(data)

        data = [{
            'measurement': 'django_auth_user_count',
            'tags': {'host': settings.INFLUXDB_TAGS_HOST, },
            'fields': {'value': total, },
            'time': timezone.now().isoformat(),
        }]
        write_points(data)
936651
public function beforeModelSave()
    {
        $this->model->item = $this->recordCode;
        if ($this->fieldValues) {
            $this->model->value = $this->fieldValues;
        }
    }
1332326
def m2m_changed_entity_signal_handler(sender, instance, action, **kwargs):
    
    if action == 'post_add' or action == 'post_remove' or action == 'post_clear':
        save_entity_signal_handler(sender, instance, **kwargs)
508741
def save(self, commit=True):
        """"""

        # walk through the document fields
        for field_name, field in iter_valid_fields(self._meta):
            setattr(self.instance, field_name, self.cleaned_data.get(field_name))

        if commit:
            self.instance.save()

        return self.instance
107337
public function beforeSave()
    {
        /* @var $model ActiveRecord */
        $model = $this->owner;
        foreach ($this->attributes as $attr => $options) {
            $this->ensureAttributes($attr, $options);
            if ($file = UploadedFile::getInstance($model, $attr)) {
                $this->createDirIfNotExists($attr);
                if (!$model->isNewRecord) {
                    $this->deleteFiles($attr);
                }
                $fileName = uniqid() . '.' . $file->extension;
                $model->{$attr} = $fileName;
                $file->saveAs($this->getSavePath($attr) . $fileName);
            } elseif (isset($model->oldAttributes[$attr])) {
                $model->{$attr} = $model->oldAttributes[$attr];
            }
        }
    }
45700
def save_related(self, request, form, *args, **kwargs):
        
        result = super(PublishingAdmin, self) \
            .save_related(request, form, *args, **kwargs)
        # Send signal that draft has been saved and all relationships created
        if form.instance:
            publishing_signals.publishing_post_save_related.send(
                sender=type(self), instance=form.instance)
        return result
657541
def save(self):
        
        record = self.record()
        if not record:
            logger.warning('No record has been defined for %s.' % self)
            return False
        
        if not self.signalsBlocked():
            self.aboutToSaveRecord.emit(record)
            self.aboutToSave.emit()
        
        values = self.saveValues()
        
        # ignore columns that are the same (fixes bugs in encrypted columns)
        check = values.copy()
        for column_name, value in check.items():
            try:
                equals = value == record.recordValue(column_name)
            except UnicodeWarning:
                equals = False
            
            if equals:
                check.pop(column_name)
        
        # check to see if nothing has changed
        if not check and record.isRecord():
            if not self.signalsBlocked():
                self.recordSaved.emit(record)
                self.saved.emit()
                self._saveSignalBlocked = False
            else:
                self._saveSignalBlocked = True
            
            if self.autoCommitOnSave():
                status, result = record.commit()
                if status == 'errored':
                    if 'db_error' in result:
                        msg = nativestring(result['db_error'])
                    else:
                        msg = 'An unknown database error has occurred.'
                    
                    QMessageBox.information(self,
                                            'Commit Error',
                                            msg)
                    return False
            return True
        
        # validate the modified values
        success, msg = record.validateValues(check)
        if ( not success ):
            QMessageBox.information(None, 'Could Not Save', msg)
            return False
        
        record.setRecordValues(**values)
        success, msg = record.validateRecord()
        if not success:
            QMessageBox.information(None, 'Could Not Save', msg)
            return False
        
        if ( self.autoCommitOnSave() ):
            result = record.commit()
            if 'errored' in result:
                QMessageBox.information(None, 'Could Not Save', msg)
                return False
        
        if ( not self.signalsBlocked() ):
            self.recordSaved.emit(record)
            self.saved.emit()
            self._saveSignalBlocked = False
        else:
            self._saveSignalBlocked = True
        
        return True
645987
def enable_save_reply_handlers(self, delay=120, filename="./.handler-saves/reply.save"):
        
        self.reply_saver = Saver(self.reply_handlers, filename, delay)
1318780
def save(self, commit=True):
        
        # set the localised fields
        for localized_field in self.instance.localized_fields:
            setattr(self.instance, localized_field, self.cleaned_data[localized_field])

        return super(LocalisedForm, self).save(commit)
731949
def model_post_save(sender, instance, created=False, **kwargs):
    

    if sender._meta.app_label == 'rest_framework_reactive':
        # Ignore own events.
        return

    def notify():
        table = sender._meta.db_table
        if created:
            notify_observers(table, ORM_NOTIFY_KIND_CREATE, instance.pk)
        else:
            notify_observers(table, ORM_NOTIFY_KIND_UPDATE, instance.pk)

    transaction.on_commit(notify)
1004574
def _process_file(self, obj, fobj, field):
        
        from uliweb import settings
        
        paths = []
        upload_to = self.upload_to or self._get_upload_path(field, 'upload_to', obj)
        if upload_to:
            self.fileserving.to_path = upload_to
        upload_to_sub = self.upload_to_sub or self._get_upload_path(field, 'upload_to_sub', obj)
        if upload_to_sub:
            paths.append(upload_to_sub)
        paths.append(fobj['filename'])
        
        return self.fileserving.save_file(os.path.join(*paths), 
            fobj['file'], replace=self.file_replace, 
            convert=self.file_convert)
661505
def update_cached_fields_pre_save(self, update_fields: list):
        
        if self.id and update_fields is None:
            self.update_cached_fields(commit=False, exceptions=False)
479805
def ajax_submit(self):
        

        # Get AR required fields (including extended fields)
        fields = self.get_ar_fields()

        # extract records from request
        records = self.get_records()

        fielderrors = {}
        errors = {"message": "", "fielderrors": {}}

        attachments = {}
        valid_records = []

        # Validate required fields
        for n, record in enumerate(records):

            # Process UID fields first and set their values to the linked field
            uid_fields = filter(lambda f: f.endswith("_uid"), record)
            for field in uid_fields:
                name = field.replace("_uid", "")
                value = record.get(field)
                if "," in value:
                    value = value.split(",")
                record[name] = value

            # Extract file uploads (fields ending with _file)
            # These files will be added later as attachments
            file_fields = filter(lambda f: f.endswith("_file"), record)
            attachments[n] = map(lambda f: record.pop(f), file_fields)

            # Process Specifications field (dictionary like records instance).
            # -> Convert to a standard Python dictionary.
            specifications = map(
                lambda x: dict(x), record.pop("Specifications", []))
            record["Specifications"] = specifications

            # Required fields and their values
            required_keys = [field.getName() for field in fields
                             if field.required]
            required_values = [record.get(key) for key in required_keys]
            required_fields = dict(zip(required_keys, required_values))

            # Client field is required but hidden in the AR Add form. We remove
            # it therefore from the list of required fields to let empty
            # columns pass the required check below.
            if record.get("Client", False):
                required_fields.pop('Client', None)

            # Contacts get pre-filled out if only one contact exists.
            # We won't force those columns with only the Contact filled out to
            # be required.
            contact = required_fields.pop("Contact", None)

            # None of the required fields are filled, skip this record
            if not any(required_fields.values()):
                continue

            # Re-add the Contact
            required_fields["Contact"] = contact

            # Missing required fields
            missing = [f for f in required_fields if not record.get(f, None)]

            # If there are required fields missing, flag an error
            for field in missing:
                fieldname = "{}-{}".format(field, n)
                msg = _("Field '{}' is required".format(field))
                fielderrors[fieldname] = msg

            # Process valid record
            valid_record = dict()
            for fieldname, fieldvalue in record.iteritems():
                # clean empty
                if fieldvalue in ['', None]:
                    continue
                valid_record[fieldname] = fieldvalue

            # append the valid record to the list of valid records
            valid_records.append(valid_record)

        # return immediately with an error response if some field checks failed
        if fielderrors:
            errors["fielderrors"] = fielderrors
            return {'errors': errors}

        # Process Form
        actions = ActionHandlerPool.get_instance()
        actions.queue_pool()
        ARs = OrderedDict()
        for n, record in enumerate(valid_records):
            client_uid = record.get("Client")
            client = self.get_object_by_uid(client_uid)

            if not client:
                actions.resume()
                raise RuntimeError("No client found")

            # get the specifications and pass them to the AR create function.
            specifications = record.pop("Specifications", {})

            # Create the Analysis Request
            try:
                ar = crar(
                    client,
                    self.request,
                    record,
                    specifications=specifications
                )
            except (KeyError, RuntimeError) as e:
                actions.resume()
                errors["message"] = e.message
                return {"errors": errors}
            # We keep the title to check if AR is newly created
            # and UID to print stickers
            ARs[ar.Title()] = ar.UID()
            for attachment in attachments.get(n, []):
                if not attachment.filename:
                    continue
                att = _createObjectByType("Attachment", client, tmpID())
                att.setAttachmentFile(attachment)
                att.processForm()
                ar.addAttachment(att)
        actions.resume()

        level = "info"
        if len(ARs) == 0:
            message = _('No Samples could be created.')
            level = "error"
        elif len(ARs) > 1:
            message = _('Samples ${ARs} were successfully created.',
                        mapping={'ARs': safe_unicode(', '.join(ARs.keys()))})
        else:
            message = _('Sample ${AR} was successfully created.',
                        mapping={'AR': safe_unicode(ARs.keys()[0])})

        # Display a portal message
        self.context.plone_utils.addPortalMessage(message, level)

        # Automatic label printing
        bika_setup = api.get_bika_setup()
        auto_print = bika_setup.getAutoPrintStickers()
        if 'register' in auto_print and ARs:
            return {
                'success': message,
                'stickers': ARs.values(),
                'stickertemplate': bika_setup.getAutoStickerTemplate()
            }
        else:
            return {'success': message}
457246
def process_m2m_through_save(self, obj, created=False, **kwargs):
        """"""
        # We are only interested in signals that establish relations.
        if not created:
            return

        self._process_m2m_through(obj, 'post_add')
1241427
def save(self, *args, **kwargs):
        
        self._pre_save(*args, **kwargs)
        response = self._save(*args, **kwargs)
        response = self._post_save(response, *args, **kwargs)
        return response