def create_initial_revisions(self, app, model_class, comment, verbosity=2, **kwargs): """Creates the set of initial revisions for the given model.""" # Import the relevant admin module. try: import_module("%s.admin" % app.__name__.rsplit(".", 1)[0]) except ImportError: pass # Check all models for empty revisions. if revision.is_registered(model_class): created_count = 0 # HACK: This join can't be done in the database, due to incompatibilities # between unicode object_ids and integer pks on strict backends like postgres. for obj in model_class._default_manager.iterator(): if Version.objects.get_for_object(obj).count() == 0: try: self.version_save(obj, comment) except: print "ERROR: Could not save initial version for %s %s." % (model_class.__name__, obj.pk) raise created_count += 1 # Print out a message, if feeling verbose. if created_count > 0 and verbosity >= 2: print u"Created %s initial revisions for model %s." % (created_count, model_class._meta.verbose_name) else: if verbosity >= 2: print u"Model %s is not registered." % (model_class._meta.verbose_name)
def create_initial_revisions(self, app, model_class, verbosity=2, **kwargs): """ all stolen from management/__init__.py :) """ # Import the relevant admin module. try: import_module("%s.admin" % app.__name__.rsplit(".", 1)[0]) except ImportError: pass # Check all models for empty revisions. if revision.is_registered(model_class): content_type = ContentType.objects.get_for_model(model_class) # Get the id for all models that have not got at least one revision. # HACK: This join can't be done in the database, for potential incompatibilities # between unicode object_ids and integer pks on strict backends like postgres. versioned_ids = frozenset(Version.objects.filter(content_type=content_type).values_list("object_id", flat=True).distinct().iterator()) all_ids = frozenset(unicode(id) for id in model_class._default_manager.values_list("pk", flat=True).iterator()) unversioned_ids = all_ids - versioned_ids # Create the initial revision for all unversioned models. created_count = 0 for unversioned_obj in model_class._default_manager.filter(pk__in=unversioned_ids).iterator(): self.version_save(unversioned_obj) created_count += 1 # Print out a message, if feeling verbose. if created_count > 0 and verbosity >= 2: self.stdout.write(u"Created %s initial revisions for model %s.\n" % (created_count, model_class._meta.verbose_name)) else: if verbosity >= 2: self.stdout.write(u"Model %s is not registered.\n" % (model_class._meta.verbose_name))
def create_initial_revisions(self, app, model_class, comment, verbosity=2, **kwargs): """Creates the set of initial revisions for the given model.""" # Import the relevant admin module. try: import_module("%s.admin" % app.__name__.rsplit(".", 1)[0]) except ImportError: pass # Check all models for empty revisions. if revision.is_registered(model_class): created_count = 0 # HACK: This join can't be done in the database, due to incompatibilities # between unicode object_ids and integer pks on strict backends like postgres. for obj in model_class._default_manager.iterator(): if Version.objects.get_for_object(obj).count() == 0: try: self.version_save(obj, comment) except: print "ERROR: Could not save initial version for %s %s." % ( model_class.__name__, obj.pk) raise created_count += 1 # Print out a message, if feeling verbose. if created_count > 0 and verbosity >= 2: print u"Created %s initial revisions for model %s." % ( created_count, model_class._meta.verbose_name) else: if verbosity >= 2: print u"Model %s is not registered." % ( model_class._meta.verbose_name)
def create_initial_revisions(app, verbosity=2, **kwargs): """ Post-syncdb hook to create an initial revision for all registered models. """ # Import the relevant admin module. try: import_module("%s.admin" % app.__name__.rsplit(".", 1)[0]) except ImportError: pass # Check all models for empty revisions. for model_class in models.get_models(app): if revision.is_registered(model_class): content_type = ContentType.objects.get_for_model(model_class) # Get the id for all models that have not got at least one revision. # HACK: This join can't be done in the database, for potential incompatibilities # between unicode object_ids and integer pks on strict backends like postgres. versioned_ids = frozenset( Version.objects.filter(content_type=content_type).values_list( "object_id", flat=True).distinct().iterator()) all_ids = frozenset( unicode(id) for id in model_class._default_manager.values_list( "pk", flat=True).iterator()) unversioned_ids = all_ids - versioned_ids # Create the initial revision for all unversioned models. created_count = 0 for unversioned_obj in model_class._default_manager.filter( pk__in=unversioned_ids).iterator(): version_save(unversioned_obj) created_count += 1 # Print out a message, if feeling verbose. if created_count > 0 and verbosity >= 2: print u"Created %s initial revisions for model %s." % ( created_count, model_class._meta.verbose_name)
def post_save_model(sender, instance, created, **kwargs): """ Функция для тригера post-save-model Сейчас нужна лишь для сохранения openness_first. """ must_register = False if revision.is_registered(instance.__class__): revision.unregister(instance.__class__) must_register = True #update task openness hook if instance.__class__ == Monitoring: for task in Task.objects.filter(organization__monitoring=instance): task.update_openness() if must_register: revision.register(instance.__class__)
def monitoring_parameter_import(request, monitoring_id): """ Импорт параметров из CSV. """ from reversion import revision must_register = False if revision.is_registered(Parameter): revision.unregister(Parameter) must_register = True monitoring = get_object_or_404(Monitoring, pk=monitoring_id) if not request.user.has_perm('exmo2010.edit_monitoring', monitoring): return HttpResponseForbidden(_('Forbidden')) if not 'paramfile' in request.FILES: return HttpResponseRedirect(reverse('exmo2010:monitoring_list')) reader = UnicodeReader(request.FILES['paramfile']) errLog = [] rowOKCount = 0 rowALLCount = 0 try: for row in reader: rowALLCount += 1 if row[0].startswith('#'): errLog.append("row %d. Starts with '#'. Skipped" % reader.line_num) continue if row[0] == '': errLog.append("row %d (csv). Empty code" % reader.line_num) continue if row[1] == '': errLog.append("row %d (csv). Empty name" % reader.line_num) continue try: code = row[0] name = row[1] parameter = Parameter.objects.get(monitoring=monitoring, code=code, name=name) except Parameter.DoesNotExist: parameter = Parameter() except Exception, e: errLog.append("row %d. %s" % (reader.line_num, e)) continue try: parameter.monitoring = monitoring parameter.code = code parameter.name = name # Присваиваем пустую строку, а не None. parameter.description = row[2] or '' parameter.complete = bool(int(row[3])) parameter.topical = bool(int(row[4])) parameter.accessible = bool(int(row[5])) parameter.hypertext = bool(int(row[6])) parameter.document = bool(int(row[7])) parameter.image = bool(int(row[8])) parameter.weight = row[9] parameter.keywords = row[10] parameter.full_clean() parameter.save() except ValidationError, e: errLog.append("row %d (validation). %s" % ( reader.line_num, '; '.join(['%s: %s' % (i[0], ', '.join(i[1])) for i in e.message_dict.items()]))) except Exception, e: errLog.append("row %d. %s" % (reader.line_num, e))
def monitoring_organization_import(request, monitoring_id): """ Импорт организаций из CSV. """ from reversion import revision must_register = False if revision.is_registered(Organization): revision.unregister(Organization) must_register = True monitoring = get_object_or_404(Monitoring, pk=monitoring_id) if not request.user.has_perm('exmo2010.edit_monitoring', monitoring): return HttpResponseForbidden(_('Forbidden')) if not 'orgfile' in request.FILES: return HttpResponseRedirect(reverse('exmo2010:monitoring_list')) reader = UnicodeReader(request.FILES['orgfile']) errLog = [] indexes = {} rowOKCount = 0 rowALLCount = 0 try: for row in reader: if rowALLCount == 0 and row[0] and row[0].startswith('#'): for key in ['name', 'url', 'email', 'phone', 'comments', 'keywords']: for item in row: if item and key in item.lower(): indexes[key] = row.index(item) continue if not 'name' in indexes: errLog.append("header row (csv). Field 'Name' does not exist") break rowALLCount += 1 if row[0] and row[0].startswith('#'): errLog.append("row %d. Starts with '#'. Skipped" % rowALLCount) continue if row[indexes['name']] == '': errLog.append("row %d (csv). Empty organization name" % rowALLCount) continue try: organization = Organization.objects.get(monitoring=monitoring, name=row[indexes['name']]) except Organization.DoesNotExist: organization = Organization() organization.monitoring = monitoring except Exception, e: errLog.append("row %d. %s" % (rowALLCount, e)) continue try: for key in indexes.keys(): cell = row[indexes[key]] if key in ['email', 'phone'] and cell: cell = replace_string(cell) setattr(organization, key, cell.strip() if cell else '') organization.inv_code = generate_inv_code(6) organization.full_clean() organization.save() except ValidationError, e: errLog.append("row %d (validation). %s" % ( rowALLCount, '; '.join(['%s: %s' % (i[0], ', '.join(i[1])) for i in e.message_dict.items()]))) except Exception, e: errLog.append("row %d. %s" % (rowALLCount, e))