def detect_soft_applied(self, project_state, migration): """ Tests whether a migration has been implicitly applied - that the tables or columns it would create exist. This is intended only for use on initial migrations (as it only looks for CreateModel and AddField). """ if migration.initial is None: # Bail if the migration isn't the first one in its app if any(app == migration.app_label for app, name in migration.dependencies): return False, project_state elif migration.initial is False: # Bail if it's NOT an initial migration return False, project_state if project_state is None: after_state = self.loader.project_state( (migration.app_label, migration.name), at_end=True) else: after_state = migration.mutate_state(project_state) apps = after_state.apps found_create_model_migration = False found_add_field_migration = False # Make sure all create model and add field operations are done for operation in migration.operations: if isinstance(operation, migrations.CreateModel): model = apps.get_model(migration.app_label, operation.name) if model._meta.swapped: # We have to fetch the model to test with from the # main app cache, as it's not a direct dependency. model = global_apps.get_model(model._meta.swapped) if model._meta.proxy or not model._meta.managed: continue if model._meta.db_table not in self.connection.introspection.table_names( self.connection.cursor()): return False, project_state found_create_model_migration = True elif isinstance(operation, migrations.AddField): model = apps.get_model(migration.app_label, operation.model_name) if model._meta.swapped: # We have to fetch the model to test with from the # main app cache, as it's not a direct dependency. model = global_apps.get_model(model._meta.swapped) if model._meta.proxy or not model._meta.managed: continue table = model._meta.db_table db_field = model._meta.get_field(operation.name).column fields = self.connection.introspection.get_table_description( self.connection.cursor(), table) if db_field not in (f.name for f in fields): return False, project_state found_add_field_migration = True # If we get this far and we found at least one CreateModel or AddField migration, # the migration is considered implicitly applied. return (found_create_model_migration or found_add_field_migration), after_state
def get_relations(m1, m2): if isinstance(m1, string_types): m1 = apps.get_model(m1) if isinstance(m2, string_types): m2 = apps.get_model(m2) return [ f for f in m1._meta.get_fields() if f.is_relation and f.related_model == m2 ]
def detect_soft_applied(self, project_state, migration): """ Tests whether a migration has been implicitly applied - that the tables or columns it would create exist. This is intended only for use on initial migrations (as it only looks for CreateModel and AddField). """ if migration.initial is None: # Bail if the migration isn't the first one in its app if any(app == migration.app_label for app, name in migration.dependencies): return False, project_state elif migration.initial is False: # Bail if it's NOT an initial migration return False, project_state if project_state is None: after_state = self.loader.project_state((migration.app_label, migration.name), at_end=True) else: after_state = migration.mutate_state(project_state) apps = after_state.apps found_create_model_migration = False found_add_field_migration = False # Make sure all create model and add field operations are done for operation in migration.operations: if isinstance(operation, migrations.CreateModel): model = apps.get_model(migration.app_label, operation.name) if model._meta.swapped: # We have to fetch the model to test with from the # main app cache, as it's not a direct dependency. model = global_apps.get_model(model._meta.swapped) if model._meta.proxy or not model._meta.managed: continue if model._meta.db_table not in self.connection.introspection.table_names(self.connection.cursor()): return False, project_state found_create_model_migration = True elif isinstance(operation, migrations.AddField): model = apps.get_model(migration.app_label, operation.model_name) if model._meta.swapped: # We have to fetch the model to test with from the # main app cache, as it's not a direct dependency. model = global_apps.get_model(model._meta.swapped) if model._meta.proxy or not model._meta.managed: continue table = model._meta.db_table db_field = model._meta.get_field(operation.name).column fields = self.connection.introspection.get_table_description(self.connection.cursor(), table) if db_field not in (f.name for f in fields): return False, project_state found_add_field_migration = True # If we get this far and we found at least one CreateModel or AddField migration, # the migration is considered implicitly applied. return (found_create_model_migration or found_add_field_migration), after_state
def fillresponse(self, model='', objid=0): img = XferCompImage('img') img.set_value(self.icon_path()) img.set_location(0, 0, 1, 6) self.add_component(img) self.model = apps.get_model(model) if objid != 0: self.item = self.model.objects.get(id=objid) fieldnames = [] for fieldname in self.model.get_default_fields(): if isinstance(fieldname, tuple): fieldnames.append(fieldname[1]) else: fieldnames.append(fieldname) self.fill_from_model(1, 0, True, desc_fields=fieldnames) log_items = LucteriosLogEntry.objects.get_for_object(self.item) else: content_type = ContentType.objects.get_for_model(self.model) lbl = XferCompLabelForm('ModelName') lbl.set_value_as_header(six.text_type(content_type)) lbl.description = _("content type") lbl.set_location(1, 0, 2) self.add_component(lbl) log_items = LucteriosLogEntry.objects.get_for_model(self.model) grid = XferCompGrid(self.field_id) grid.set_model(log_items, None, self) grid.set_location(1, self.get_max_row() + 1, 2) grid.set_size(200, 500) self.add_component(grid)
def detect_soft_applied(self, project_state, migration): """ Tests whether a migration has been implicitly applied - that the tables it would create exist. This is intended only for use on initial migrations (as it only looks for CreateModel). """ # Bail if the migration isn't the first one in its app if [name for app, name in migration.dependencies if app == migration.app_label]: return False, project_state if project_state is None: after_state = self.loader.project_state((migration.app_label, migration.name), at_end=True) else: after_state = migration.mutate_state(project_state) apps = after_state.apps found_create_migration = False # Make sure all create model are done for operation in migration.operations: if isinstance(operation, migrations.CreateModel): model = apps.get_model(migration.app_label, operation.name) if model._meta.swapped: # We have to fetch the model to test with from the # main app cache, as it's not a direct dependency. model = global_apps.get_model(model._meta.swapped) if model._meta.db_table not in self.connection.introspection.table_names(self.connection.cursor()): return False, project_state found_create_migration = True # If we get this far and we found at least one CreateModel migration, # the migration is considered implicitly applied. return found_create_migration, after_state
def run(self, module_name, class_name, trace, fields=None, extra_fields=None, exclude_fields=None, native=False, limits=(0, None)): model = apps.get_model(module_name, class_name) qs = model.objects.get_queryset() exclude_fields = list(exclude_fields or ()) extra_fields = list(extra_fields or ()) fields = list(fields or []) if extra_fields or exclude_fields or not fields: fields = self.get_fields(model) fields = [f for f in fields + extra_fields if f not in exclude_fields ] or '__all__' qs = self.trace_queryset(qs, trace) if native: if isinstance(qs, QuerySet): return list(qs) return qs if tuple(limits) != (0, None): start, stop = limits qs = qs[slice(start, stop)] return self.serialize(qs, model=model, fields=fields, extra_fields=extra_fields)
def get_model_field_verbose_name_map(m): if isinstance(m, string_types): m = apps.get_model(m) r = {} for f in m._meta.get_fields(): r[get_field_verbose_name(f)] = f return r
def detect_soft_applied(self, project_state, migration): """ Tests whether a migration has been implicitly applied - that the tables it would create exist. This is intended only for use on initial migrations (as it only looks for CreateModel). """ # Bail if the migration isn't the first one in its app if [ name for app, name in migration.dependencies if app == migration.app_label ]: return False, project_state if project_state is None: after_state = self.loader.project_state( (migration.app_label, migration.name), at_end=True) else: after_state = migration.mutate_state(project_state) apps = after_state.apps found_create_migration = False # Make sure all create model are done for operation in migration.operations: if isinstance(operation, migrations.CreateModel): model = apps.get_model(migration.app_label, operation.name) if model._meta.swapped: # We have to fetch the model to test with from the # main app cache, as it's not a direct dependency. model = global_apps.get_model(model._meta.swapped) if model._meta.db_table not in self.connection.introspection.table_names( self.connection.cursor()): return False, project_state found_create_migration = True # If we get this far and we found at least one CreateModel migration, # the migration is considered implicitly applied. return found_create_migration, after_state
def get_subtitle(): try: from django.apps.registry import apps legalentity = apps.get_model("contacts", "LegalEntity") our_detail = legalentity.objects.get(id=1) return our_detail.name except LookupError: return ugettext("Condominium application")
def fillresponse(self, modelname, field_id): if modelname is not None: self.model = apps.get_model(modelname) self.field_id = field_id XferListEditor.fillresponse(self) if WrapAction.is_permission(self.request, 'contacts.add_abstractcontact'): self.get_components(self.field_id).add_action(self.request, ObjectMerge.get_action(_("Merge"), "images/clone.png"), close=CLOSE_NO, unique=SELECT_MULTI)
def get_typeselection(cls): res = [] for modelname in cls.objects.values_list('modelname', flat=True).distinct(): model_item = apps.get_model(modelname) res.append( (modelname, six.text_type(model_item._meta.verbose_name))) return sorted(list(set(res)), key=lambda item: item[1])
def find(app_label, model_name): if not app_label: raise CommandError('Invalid app label "{}"'.format(app_label)) if not model_name: raise CommandError('Invalid model name "{}"'.format(model_name)) return apps.get_model(app_label, model_name)
def get(self, request, app, model): Model = apps.get_model(app, model) if self.has_export_permission(request.user, Model): return queryset_as_csv_response(Model.objects.all(), is_stream=True) else: raise PermissionDenied
def get_model(self, table_name): # Ensure the database connect and it's dummy app are registered self.register() model_name = table_name.lower().replace('_', '') # Is the model already registered with the dummy app? if model_name not in apps.all_models[self.label]: logger.info('Adding dynamic model: %s %s', self.label, table_name) # Use the "inspectdb" management command to get the structure of the table for us. file_obj = BufferWriter() kwargs = { 'database': self.label, 'table_name_filter': lambda t: t == table_name } if VERSION[0] >= 1 and VERSION[1] >= 10: kwargs['table'] = [table_name] Command(stdout=file_obj).handle(**kwargs) model_definition = file_obj.data # Make sure that we found the table and have a model definition loc = model_definition.find('(models.Model):') if loc != -1: # Ensure that the Model has a primary key. # Django doesn't support multiple column primary keys, # So we have to add a primary key if the inspect command didn't if model_definition.find('primary_key', loc) == -1: loc = model_definition.find('(', loc + 14) model_definition = '{}primary_key=True, {}'.format( model_definition[:loc + 1], model_definition[loc + 1:]) # Ensure that the model specifies what app_label it belongs to loc = model_definition.find( 'db_table = \'{}\''.format(table_name)) if loc != -1: model_definition = '{}app_label = \'{}\'\n {}'.format( model_definition[:loc], self.label, model_definition[loc:]) # Register the model with Django. Sad day when we use 'exec' exec(model_definition, globals(), locals()) # exec model_definition in globals(), locals() # Update the list of models that the app # has to match what Django now has for this app apps.app_configs[self.label].models = apps.all_models[ self.label] else: logger.info('Could not find table: %s %s', self.label, table_name) else: logger.info('Already added dynamic model: %s %s', self.label, table_name) # If we have the connection, app and model. Return the model class if (self.label in connections._databases and self.label in apps.all_models and model_name in apps.all_models[self.label]): return apps.get_model(self.label, model_name)
def render(self, context): model = apps.get_model(*self.model.split('.')) if model is None: raise TemplateSyntaxError( _('tag_cloud_for_model tag was given an invalid model: %s') % self.model) context[self.context_var] = Tag.objects.cloud_for_model( model, **self.kwargs) return ''
def render(self, context): model = apps.get_model(*self.model.split('.')) if model is None: raise TemplateSyntaxError( _('tagged_objects tag was given an invalid model: %s') % self.model) context[self.context_var] = TaggedItem.objects.get_by_model( model, self.tag.resolve(context)) return ''
def get_message(self): def get_new_line(action, dep_field, value): if hasattr(dep_field, 'verbose_name'): title = dep_field.verbose_name else: title = dep_field.name if action in (self.Action.CREATE, self.Action.ADD) or (value[0] == value[1]): return '%s: "%s"' % (title, get_format_value(dep_field, value[1])) elif action == self.Action.UPDATE: return '%s: "%s" -> "%s"' % ( title, get_format_value(dep_field, value[0]), get_format_value(dep_field, value[1])) else: return '%s: "%s"' % (title, get_format_value(dep_field, value[0])) changes = json.loads(self.changes) res = [] for key, value in changes.items(): dep_field = self.get_field(key) if (dep_field is None) or (not dep_field.editable or dep_field.primary_key): continue res.append(get_new_line(self.action, dep_field, value)) if self.additional_data is not None: additional_data = json.loads(self.additional_data) for field_title, values in additional_data.items(): for action_id, value_data in values.items(): action_id = int(action_id) res_data = [] for value_item in value_data: if isinstance(value_item, dict) and ( 'modelname' in value_item) and ('changes' in value_item): sub_model = apps.get_model(value_item['modelname']) for sub_fieldname, diff_value in value_item[ 'changes'].items(): sub_dep_field = sub_model._meta.get_field( sub_fieldname) if (sub_dep_field is None) or ( not sub_dep_field.editable or sub_dep_field.primary_key): continue res_data.append( get_new_line(action_id, sub_dep_field, diff_value)) else: res_data.append(value_item) res.append( '%s: %s = "%s"' % (field_title, LucteriosLogEntry.Action.get_action_title(action_id), '" "'.join(res_data))) return res
def get_model(self, table_name): # Ensure the database connect and it's dummy app are registered self.register() model_name = table_name.lower().replace('_', '') # Is the model already registered with the dummy app? if model_name not in apps.all_models[self.label]: logger.info('Adding dynamic model: %s %s', self.label, table_name) # Use the "inspectdb" management command to get the structure of the table for us. file_obj = BufferWriter() kwargs = { 'database': self.label, 'table_name_filter': lambda t: t == table_name } if VERSION[0] >= 1 and VERSION[1] >= 10: kwargs['table'] = [table_name] Command(stdout=file_obj).handle(**kwargs) model_definition = file_obj.data # Make sure that we found the table and have a model definition loc = model_definition.find('(models.Model):') if loc != -1: # Ensure that the Model has a primary key. # Django doesn't support multiple column primary keys, # So we have to add a primary key if the inspect command didn't if model_definition.find('primary_key', loc) == -1: loc = model_definition.find('(', loc + 14) model_definition = '{}primary_key=True, {}'.format( model_definition[:loc + 1], model_definition[loc + 1:] ) # Ensure that the model specifies what app_label it belongs to loc = model_definition.find('db_table = \'{}\''.format(table_name)) if loc != -1: model_definition = '{}app_label = \'{}\'\n {}'.format( model_definition[:loc], self.label, model_definition[loc:] ) # Register the model with Django. Sad day when we use 'exec' exec(model_definition, globals(), locals()) # exec model_definition in globals(), locals() # Update the list of models that the app # has to match what Django now has for this app apps.app_configs[self.label].models = apps.all_models[self.label] else: logger.info('Could not find table: %s %s', self.label, table_name) else: logger.info('Already added dynamic model: %s %s', self.label, table_name) # If we have the connection, app and model. Return the model class if ( self.label in connections._databases and self.label in apps.all_models and model_name in apps.all_models[self.label] ): return apps.get_model(self.label, model_name)
def get_model_list(class_list): """ Receives a list of strings with app_name.model_name format and turns them into classes. If an item is already a class it ignores it. """ for idx, item in enumerate(class_list): if isinstance(item, six.string_types): model_class = apps.get_model(item) class_list[idx] = model_class
def run(self, module_name, class_name, kwargs, update=False): model = apps.get_model(module_name, class_name) qs = model.objects.get_queryset() if update: obj, created = qs.update_or_create(**kwargs) else: obj, created = qs.get_or_create(**kwargs) data = self.serialize(obj, model=model) return data, created
def get_model_list(class_list): """ Receives a list of strings or arrays or classes. If an item is a string with app_name.model_name format, it is turned into classes. If an item is a list with (app_name, model_name,) format, it is turned into classes. If an item is already a class it ignores it. """ for idx, item in enumerate(class_list): if isinstance(item, six.string_types): model_class = apps.get_model(item) class_list[idx] = model_class if isinstance(item, (list, tuple)): model_class = apps.get_model(item[0], item[1]) class_list[idx] = model_class
def get_models(): from django.apps.registry import apps r = {} for a, b, c in router.registry: try: m = apps.get_model(a.replace('/', '.')) r[m._meta.label_lower] = m except: pass return r
def handle(self, *args, **kwargs): app_label, model_name = kwargs["model_label"].lower().rsplit(".") try: model = apps.get_model(app_label, model_name) except LookupError as e: raise CommandError(str(e)) fixture_filepath = pathlib.Path(settings.BASE_DIR).joinpath( app_label, "fixtures", f"{model._meta.verbose_name_plural}.jsonl") self.atomically_loadlines(model, fixture_filepath)
def get_or_create_concrete_model(model): """ Returns the concrete version of argument model. Argument model may be a concrete model, in which case, it is returned as is. Otherwise a concrete model programmatically created from argument model is returned. """ try: return apps.get_model(model._meta.label_lower) except LookupError: return ModelBase(model.__name__, (model,), {"__module__": model.__module__})
def display_name(self): if self.name: return self.name if self.page == "list": try: app_label, model_name = self.model.split("__", maxsplit=1) model = apps.get_model(app_label, model_name) return model._meta.verbose_name + "管理" except: pass return "未命名"
def display_name(self): if self.name: return self.name if self.page == 'list': try: app_label, model_name = self.model.split('__', maxsplit=1) model = apps.get_model(app_label, model_name) return model._meta.verbose_name + '管理' except: pass return '未命名'
def get_model_viewsets(): from django.apps.registry import apps r = {} for a, b, c in router.registry: try: mn = a.replace('/', '.') if hasattr(b, 'queryset'): m = b.queryset.model else: m = apps.get_model(mn) r[mn] = b except: pass return r
def run(self, module_name, class_name, trace, updates, single=False): model = apps.get_model(module_name, class_name) # noinspection PyProtectedMember pk_name = model._meta.pk.attname updates.pop(pk_name, None) qs = model.objects.get_queryset() qs = self.trace_queryset(qs, trace) if single: instance = qs.get() for k, v in updates.items(): setattr(instance, k, v) instance.save(update_fields=list(updates.keys())) return 1 return qs.update(**updates)
def get_event_model(): """ Helper for getting event swappable model. :return: :class:`Event` model """ model_path = settings.EVENT_MODEL swappable = apps.get_model(model_path) if not issubclass(swappable, AbstractBaseEvent): raise ImproperlyConfigured( "Given %s model isn't subclass of AbstractBaseUser" % model_path ) return swappable
def get_queryset(self, pks): queryset = None if self.queryset is not None: queryset = self.queryset if hasattr(queryset, '_clone'): queryset = queryset._clone() elif self.model is not None: if isinstance(self.model, basestring): app, model_name = self.model.split('.') queryset = apps.get_model(app, model_name).objects else: queryset = self.model.objects else: raise self.Misconfigured('missing_model_queryset') filter = {'%s__in' % self.pk_field: pks} return queryset.filter(**filter)
def gen_relation_lookup_from_request(self, request): pms = request.query_params d = {} for k, v in pms.items(): ps = k.split('.') if len(ps) != 3: continue mn = '.'.join(ps[:2]) try: m = apps.get_model(mn) fn = ps[2] m._meta.get_field(fn) d.setdefault(mn, {})[fn] = v except: pass return d
def get_text_from_instance(self): try: from django.apps.registry import apps legalentity = apps.get_model("contacts", "LegalEntity") instance_name = legalentity.objects.get(id=1) except LookupError: from django.conf import settings instance_name = basename(dirname(settings.SETUP.__file__)) xml_text = convert_to_html('text', "{[b]}{[u]}%s{[/u]}{[/b]}" % instance_name, text_align='center') xml_text.attrib['height'] = "%d.0" % 12 xml_text.attrib['width'] = "%d.0" % self.content_width xml_text.attrib['top'] = "0.0" xml_text.attrib['left'] = "0.0" return xml_text
def get_permissions_for_staff_user(): """ Returns all permissions that staff user possess. Staff user can create and edit all models from `MODELS_STAFF_USER_CAN_EDIT` list. By design he has no delete privileges --- as deleting questions could lead to bad user experience for students. :return: Iterable[django.contrib.auth.models.Permission] """ from django.apps.registry import apps for app_label, model_name in MODELS_STAFF_USER_CAN_EDIT: model = apps.get_model(app_label, model_name) for action in ('add', 'change'): codename = get_permission_codename(action, model._meta) yield Permission.objects.get_by_natural_key(codename, app_label, model_name)
def fillresponse(self): if self.getparam("CONFIRME") is None: dlg = self.create_custom() img = XferCompImage('img') img.set_value(self.icon_path()) img.set_location(0, 0) dlg.add_component(img) lbl = XferCompLabelForm('title') lbl.set_value_as_title(self.caption) lbl.set_location(1, 0, 2) dlg.add_component(lbl) lbl = XferCompLabelForm('lbl_record') lbl.set_value_as_name(_('record')) lbl.set_location(1, 1) dlg.add_component(lbl) lbl = XferCompLabelForm('record') lbl.set_value(six.text_type(self.item)) lbl.set_location(2, 1) dlg.add_component(lbl) lbl = XferCompLabelForm('lbl_current') lbl.set_value_as_name(_('current model')) lbl.set_location(1, 2) dlg.add_component(lbl) lbl = XferCompLabelForm('current') lbl.set_value(self.item.__class__._meta.verbose_name) lbl.set_location(2, 2) dlg.add_component(lbl) lbl = XferCompLabelForm('lbl_newmodel') lbl.set_value_as_name(_('new model')) lbl.set_location(1, 3) dlg.add_component(lbl) lbl = XferCompSelect('newmodel') lbl.set_select(self.item.__class__.get_select_contact_type(False)) lbl.set_location(2, 3) dlg.add_component(lbl) dlg.add_action(self.get_action(_('Ok'), "images/ok.png"), {'close': CLOSE_YES, 'modal': FORMTYPE_MODAL, 'params': {'CONFIRME': 'YES'}}) dlg.add_action(WrapAction(_("Cancel"), "images/cancel.png"), {}) else: new_model = apps.get_model(self.getparam('newmodel')) field_id_name = "%s_ptr_id" % self.model.__name__.lower() new_object = new_model(**{field_id_name: self.item.pk}) new_object.save() new_object.__dict__.update(self.item.__dict__) new_object.save() self.redirect_action( ActionsManage.get_act_changed(self.model.__name__, 'show', '', ''), {})
def get_field_by_param(self, param): field_args = param.param_type.split('.') if len(field_args) == 2: app_name = field_args[0] model_name = field_args[1] model = apps.get_model(app_name, model_name) field = serializers.PrimaryKeyRelatedField( queryset=model.objects.all(), many=bool(param.is_many)) elif len(field_args) == 1: serializer_field_name = self.parameter_model.PARAMETERS_TYPES[ param.param_type]['serializer_field_name'] field = getattr(serializers, serializer_field_name)() else: raise serializers.ValidationError( f'''can't validate class for field"{param.code}"''') field.required = param.is_required return field
def fillresponse(self): if self.getparam("CONFIRME") is None: dlg = self.create_custom() img = XferCompImage('img') img.set_value(self.icon_path()) img.set_location(0, 0) dlg.add_component(img) lbl = XferCompLabelForm('title') lbl.set_value_as_title(self.caption) lbl.set_location(1, 0, 2) dlg.add_component(lbl) lbl = XferCompLabelForm('lbl_record') lbl.set_value_as_name(_('record')) lbl.set_location(1, 1) dlg.add_component(lbl) lbl = XferCompLabelForm('record') lbl.set_value(six.text_type(self.item)) lbl.set_location(2, 1) dlg.add_component(lbl) lbl = XferCompLabelForm('lbl_current') lbl.set_value_as_name(_('current model')) lbl.set_location(1, 2) dlg.add_component(lbl) lbl = XferCompLabelForm('current') lbl.set_value(self.item.__class__._meta.verbose_name) lbl.set_location(2, 2) dlg.add_component(lbl) lbl = XferCompLabelForm('lbl_newmodel') lbl.set_value_as_name(_('new model')) lbl.set_location(1, 3) dlg.add_component(lbl) lbl = XferCompSelect('newmodel') lbl.set_select(self.item.__class__.get_select_contact_type(False)) lbl.set_location(2, 3) dlg.add_component(lbl) dlg.add_action(self.get_action(_('Ok'), "images/ok.png"), close=CLOSE_YES, modal=FORMTYPE_MODAL, params={'CONFIRME': 'YES'}) dlg.add_action(WrapAction(_("Cancel"), "images/cancel.png")) else: new_model = apps.get_model(self.getparam('newmodel')) field_id_name = "%s_ptr_id" % self.model.__name__.lower() new_object = new_model(**{field_id_name: self.item.pk}) new_object.save() new_object.__dict__.update(self.item.__dict__) new_object.save() self.redirect_action(ActionsManage.get_action_url(self.model.get_long_name(), 'Show', self))
def create_empty_class(model, bases): ''' Returns an empty class with the right metadata ''' name = name_history_model(model.__name__) try: return apps.get_model(model._meta.app_label, name) except AppRegistryNotReady: class Meta: app_label = model._meta.app_label abstract = False verbose_name = _('%s change history') % model._meta.verbose_name verbose_name_plural = _('%s change histories') % model._meta.verbose_name attrs = {} attrs["Meta"] = Meta attrs["__module__"] = model.__module__ return type(str(name), bases, attrs)
def detect_soft_applied(self, migration): """ Tests whether a migration has been implicitly applied - that the tables it would create exist. This is intended only for use on initial migrations (as it only looks for CreateModel). """ project_state = self.loader.project_state((migration.app_label, migration.name), at_end=True) apps = project_state.render() found_create_migration = False for operation in migration.operations: if isinstance(operation, migrations.CreateModel): model = apps.get_model(migration.app_label, operation.name) if model._meta.swapped: # We have to fetch the model to test with from the # main app cache, as it's not a direct dependency. model = global_apps.get_model(model._meta.swapped) if model._meta.db_table not in self.connection.introspection.get_table_list(self.connection.cursor()): return False found_create_migration = True # If we get this far and we found at least one CreateModel migration, # the migration is considered implicitly applied. return found_create_migration
def detect_soft_applied(self, project_state, migration): """ Tests whether a migration has been implicitly applied - that the tables or columns it would create exist. This is intended only for use on initial migrations (as it only looks for CreateModel and AddField). """ def should_skip_detecting_model(migration, model): """ No need to detect tables for proxy models, unmanaged models, or models that can't be migrated on the current database. """ return ( model._meta.proxy or not model._meta.managed or not router.allow_migrate( self.connection.alias, migration.app_label, model_name=model._meta.model_name, ) ) if migration.initial is None: # Bail if the migration isn't the first one in its app if any(app == migration.app_label for app, name in migration.dependencies): return False, project_state elif migration.initial is False: # Bail if it's NOT an initial migration return False, project_state if project_state is None: after_state = self.loader.project_state((migration.app_label, migration.name), at_end=True) else: after_state = migration.mutate_state(project_state) apps = after_state.apps found_create_model_migration = False found_add_field_migration = False existing_table_names = self.connection.introspection.table_names(self.connection.cursor()) # Make sure all create model and add field operations are done for operation in migration.operations: if isinstance(operation, migrations.CreateModel): model = apps.get_model(migration.app_label, operation.name) if model._meta.swapped: # We have to fetch the model to test with from the # main app cache, as it's not a direct dependency. model = global_apps.get_model(model._meta.swapped) if should_skip_detecting_model(migration, model): continue if model._meta.db_table not in existing_table_names: return False, project_state found_create_model_migration = True elif isinstance(operation, migrations.AddField): model = apps.get_model(migration.app_label, operation.model_name) if model._meta.swapped: # We have to fetch the model to test with from the # main app cache, as it's not a direct dependency. model = global_apps.get_model(model._meta.swapped) if should_skip_detecting_model(migration, model): continue table = model._meta.db_table field = model._meta.get_field(operation.name) # Handle implicit many-to-many tables created by AddField. if field.many_to_many: if field.remote_field.through._meta.db_table not in existing_table_names: return False, project_state else: found_add_field_migration = True continue column_names = [ column.name for column in self.connection.introspection.get_table_description(self.connection.cursor(), table) ] if field.column not in column_names: return False, project_state found_add_field_migration = True # If we get this far and we found at least one CreateModel or AddField migration, # the migration is considered implicitly applied. return (found_create_model_migration or found_add_field_migration), after_state
def _search_model(self): modelname = self.getparam('modelname') self.model = apps.get_model(modelname) XferContainerAcknowledge._search_model(self)
def _search_model(self): modelname = self.getparam('modelname') self.model = apps.get_model(modelname) self.field_id = self.getparam('field_id', modelname.lower()) XferContainerAcknowledge._search_model(self)
def get_model(model_label): return registered_apps.get_model(model_label)
def orm_metadata(self, export_format): ''' ''' model = apps.get_model(self.module, self.name) model_opts = model._meta old_project_state = ProjectState() new_project_state = ProjectState() # new_project_state.add_model(model) autodetector = MigrationAutodetector(old_project_state, new_project_state) autodetector.generated_operations = {} # code from MigrationAutodetector.generate_created_models # Gather related fields related_fields = {} primary_key_rel = None for field in model_opts.local_fields: if field.rel: if field.rel.to: if field.primary_key: primary_key_rel = field.rel.to elif not field.rel.parent_link: related_fields[field.name] = field # through will be none on M2Ms on swapped-out models; # we can treat lack of through as auto_created=True, though. if getattr(field.rel, "through", None) and not field.rel.through._meta.auto_created: related_fields[field.name] = field for field in model_opts.local_many_to_many: if field.rel.to: related_fields[field.name] = field if getattr(field.rel, "through", None) and not field.rel.through._meta.auto_created: related_fields[field.name] = field # Are there unique/index_together to defer? # unique_together = model_state.options.pop('unique_together', None) # index_together = model_state.options.pop('index_together', None) # order_with_respect_to = model_state.options.pop('order_with_respect_to', None) # Depend on the deletion of any possible proxy version of us dependencies = [ (self.module, self.name, None, False), ] # Depend on all bases # for base in model_state.bases: # if isinstance(base, six.string_types) and "." in base: # base_app_label, base_name = base.split(".", 1) # dependencies.append((base_app_label, base_name, None, True)) # Depend on the other end of the primary key if it's a relation if primary_key_rel: dependencies.append(( primary_key_rel._meta.app_label, primary_key_rel._meta.object_name, None, True )) # Generate creation operation autodetector.add_operation( self.module, operations.CreateModel( name=self.name, fields=[d for d in model_opts.fields if d not in related_fields.values()], options=model_opts, bases=self.__class__.__bases__, managers=model_opts.managers, ), dependencies=dependencies, beginning=True, ) # autodetector.generated_operations metadata = None fields = [] if export_format == 'XML': metadata = "<Fields>" if export_format == 'JSON': metadata = '"Fields": [' if export_format == 'DICT': metadata = {} for field in autodetector.generated_operations[self.module][0].fields: if export_format == 'XML': sf = '<Field name="' + field.name + '">' sf += "</Field>" if export_format == 'JSON': sf = '{"name": "' + field.name + '", "type": "' + field.__class__.__name__ + '", "null": "' + str(field.null) + '"' if field.max_length != None: sf += ', "max_length": "' + str(field.max_length) + '"' sf += ', "is_relation": "' + str(field.is_relation) + '", "column": "' + field.column + '"' if field.default not in {None, NOT_PROVIDED}: sf += ', "default": "' + str(field.default) + '"' sf += '}' if export_format == 'DICT': sf = {"name": field.name} fields.append(sf) field.many_to_many field.many_to_one if export_format == 'XML': metadata += " ".join(fields) + "</Fields>" if export_format == 'JSON': metadata += ", ".join(fields) + "]" if export_format == 'DICT': metadata['Fields'] = fields return metadata
from __future__ import unicode_literals
def post_comment_ajax(request, using=None): """ Post a comment, via an Ajax call. """ if not request.is_ajax(): return HttpResponseBadRequest("Expecting Ajax call") # This is copied from django_comments. # Basically that view does too much, and doesn't offer a hook to change the rendering. # The request object is not passed to next_redirect for example. # # This is a separate view to integrate both features. Previously this used django-ajaxcomments # which is unfortunately not thread-safe (it it changes the comment view per request). # Fill out some initial data fields from an authenticated user, if present data = request.POST.copy() if request.user.is_authenticated(): if not data.get('name', ''): data["name"] = request.user.get_full_name() or request.user.username if not data.get('email', ''): data["email"] = request.user.email # Look up the object we're trying to comment about ctype = data.get("content_type") object_pk = data.get("object_pk") if ctype is None or object_pk is None: return CommentPostBadRequest("Missing content_type or object_pk field.") try: object_pk = long(object_pk) try: from django.db import models model = models.get_model(*ctype.split(".", 1)) except: from django.apps.registry import apps model = apps.get_model(*ctype.split(".", 1)) target = model._default_manager.using(using).get(pk=object_pk) except ValueError: return CommentPostBadRequest("Invalid object_pk value: {0}".format(escape(object_pk))) except TypeError: return CommentPostBadRequest("Invalid content_type value: {0}".format(escape(ctype))) except AttributeError: return CommentPostBadRequest("The given content-type {0} does not resolve to a valid model.".format(escape(ctype))) except ObjectDoesNotExist: return CommentPostBadRequest("No object matching content-type {0} and object PK {1} exists.".format(escape(ctype), escape(object_pk))) except (ValueError, ValidationError) as e: return CommentPostBadRequest("Attempting go get content-type {0!r} and object PK {1!r} exists raised {2}".format(escape(ctype), escape(object_pk), e.__class__.__name__)) # Do we want to preview the comment? preview = "preview" in data # Construct the comment form form = get_comments_form()(target, data=data) # Check security information if form.security_errors(): return CommentPostBadRequest("The comment form failed security verification: {0}".format(form.security_errors())) # If there are errors or if we requested a preview show the comment if preview: comment = form.get_comment_object() if not form.errors else None return _ajax_result(request, form, "preview", comment, object_id=object_pk) if form.errors: return _ajax_result(request, form, "post", object_id=object_pk) # Otherwise create the comment comment = form.get_comment_object() comment.ip_address = request.META.get("REMOTE_ADDR", None) if request.user.is_authenticated(): comment.user = request.user # Signal that the comment is about to be saved responses = signals.comment_will_be_posted.send( sender = comment.__class__, comment = comment, request = request ) for (receiver, response) in responses: if response is False: return CommentPostBadRequest("comment_will_be_posted receiver {0} killed the comment".format(receiver.__name__)) # Save the comment and signal that it was saved comment.save() signals.comment_was_posted.send( sender = comment.__class__, comment = comment, request = request ) return _ajax_result(request, form, "post", comment, object_id=object_pk)