def create_history_model(self, model): """ Creates a historical model to associate with the model provided. """ attrs = {'__module__': self.module} app_module = '%s.models' % model._meta.app_label if model.__module__ != self.module: # registered under different app attrs['__module__'] = self.module elif app_module != self.module: if apps is None: # Django < 1.7 # has meta options with app_label app = loading.get_app(model._meta.app_label) attrs['__module__'] = app.__name__ # full dotted name else: # Abuse an internal API because the app registry is loading. app = apps.app_configs[model._meta.app_label] attrs['__module__'] = app.name # full dotted name fields = self.copy_fields(model) attrs.update(fields) attrs.update(self.get_extra_fields(model, fields)) # type in python2 wants str as a first argument attrs.update(Meta=type(str('Meta'), (), self.get_meta_options(model))) name = 'Historical%s' % model._meta.object_name registered_models[model._meta.db_table] = model return python_2_unicode_compatible( type(str(name), self.bases, attrs))
def create_history_model(self, model): """ Creates a historical model to associate with the model provided. """ attrs = {'__module__': self.module} app_module = '%s.models' % model._meta.app_label if model.__module__ != self.module: # registered under different app attrs['__module__'] = self.module elif app_module != self.module: try: # Abuse an internal API because the app registry is loading. app = apps.app_configs[model._meta.app_label] except NameError: # Django < 1.7 models_module = get_app(model._meta.app_label).__name__ else: models_module = app.name attrs['__module__'] = models_module fields = self.copy_fields(model) attrs.update(fields) attrs.update(self.get_extra_fields(model, fields)) # type in python2 wants str as a first argument attrs.update(Meta=type(str('Meta'), (), self.get_meta_options(model))) if self.table_name is not None: attrs['Meta'].db_table = self.table_name name = 'Historical%s' % model._meta.object_name registered_models[model._meta.db_table] = model return python_2_unicode_compatible(type(str(name), self.bases, attrs))
def create_history_model(self, model, inherited): """ Creates a historical model to associate with the model provided. """ attrs = {'__module__': self.module} app_module = '%s.models' % model._meta.app_label if inherited: # inherited use models module attrs['__module__'] = model.__module__ elif model.__module__ != self.module: # registered under different app attrs['__module__'] = self.module elif app_module != self.module: # Abuse an internal API because the app registry is loading. app = apps.app_configs[model._meta.app_label] models_module = app.name attrs['__module__'] = models_module fields = self.copy_fields(model) attrs.update(fields) attrs.update(self.get_extra_fields(model, fields)) # type in python2 wants str as a first argument attrs.update(Meta=type(str('Meta'), (), self.get_meta_options(model))) if self.table_name is not None: attrs['Meta'].db_table = self.table_name name = 'Historical%s' % model._meta.object_name registered_models[model._meta.db_table] = model return python_2_unicode_compatible( type(str(name), self.bases, attrs))
def create_history_model(self, model, inherited): """ Creates a historical model to associate with the model provided. """ attrs = { "__module__": self.module, "_history_excluded_fields": self.excluded_fields, } app_module = "%s.models" % model._meta.app_label if inherited: # inherited use models module attrs["__module__"] = model.__module__ elif model.__module__ != self.module: # registered under different app attrs["__module__"] = self.module elif app_module != self.module: # Abuse an internal API because the app registry is loading. app = apps.app_configs[model._meta.app_label] models_module = app.name attrs["__module__"] = models_module fields = self.copy_fields(model) attrs.update(fields) attrs.update(self.get_extra_fields(model, fields)) # type in python2 wants str as a first argument attrs.update(Meta=type(str("Meta"), (), self.get_meta_options(model))) if self.table_name is not None: attrs["Meta"].db_table = self.table_name name = (self.custom_model_name if self.custom_model_name is not None else "Historical%s" % model._meta.object_name) registered_models[model._meta.db_table] = model return python_2_unicode_compatible(type(str(name), self.bases, attrs))
def test_unicode_dunder_compat(): app_settings.COPY_UNICODE = False assert hasattr(StrHasDunderUnicodeCompat, '__str__') assert not hasattr(StrHasDunderUnicodeCompat, '__unicode__') orig_str_func = StrHasDunderUnicodeCompat.__str__ StrHasDunderUnicodeWrapped = python_2_unicode_compatible( StrHasDunderUnicodeCompat) assert hasattr(StrHasDunderUnicodeWrapped, '__str__') if PY3: assert not hasattr(StrHasDunderUnicodeWrapped, '__unicode__') else: assert hasattr(StrHasDunderUnicodeWrapped, '__unicode__') # python_2_unicode_compatible moves __str__ to __unicode__, # and creates a safe __str__ if PY3: assert StrHasDunderUnicodeWrapped.__str__ == orig_str_func assert not hasattr(StrHasDunderUnicodeWrapped, '__unicode__') else: assert StrHasDunderUnicodeWrapped.__unicode__ == orig_str_func assert StrHasDunderUnicodeWrapped.__str__ != orig_str_func str_func = StrHasDunderUnicodeCompat.__str__ if not PY3: unicode_func = StrHasDunderUnicodeCompat.__unicode__ assert not _has_default_str(StrHasDunderUnicodeWrapped) assert StrHasDunderUnicodeCompat.__str__ == str_func if PY3: assert not hasattr(StrHasDunderUnicodeWrapped, '__unicode__') else: assert StrHasDunderUnicodeCompat.__unicode__ == unicode_func item = StrHasDunderUnicodeWrapped.objects.create() assert str(item) == 'model.__str__' if not PY3: assert unicode(item) == 'model.__str__' app_settings.COPY_UNICODE = True assert not _has_default_str(StrHasDunderUnicodeWrapped) # Check nothing changed assert StrHasDunderUnicodeCompat.__str__ == str_func if PY3: assert not hasattr(StrHasDunderUnicodeWrapped, '__unicode__') else: assert StrHasDunderUnicodeCompat.__unicode__ == unicode_func app_settings.COPY_UNICODE = False
def create_fake_m2m(self, model): if not self.is_m2m: for attr in dir(model): if hasattr(model, attr) and hasattr(getattr(model, attr), 'field'): fld = getattr(model, attr).field if fld.is_relation and not fld.many_to_many and \ fld.rel.model.__name__ in registered_historical_models and \ not registered_historical_models[fld.rel.model.__name__].is_m2m: to_model = fld.rel.model if fld.rel.related_name == '+': continue if fld.rel.related_name is not None: to_name = fld.rel.related_name else: to_name = '{}_set'.format(fld.rel.name) from_model = model from_name = fld.name else: continue elif hasattr(model, attr) and hasattr(getattr(model, attr), 'related'): rel = getattr(model, attr).related if rel.is_relation and not rel.field.many_to_many and \ rel.field.model.__name__ in registered_historical_models and \ not registered_historical_models[rel.field.model.__name__].is_m2m: from_model = rel.field.model from_name = rel.field.name to_model = model to_name = attr else: continue else: continue to_hist_model = registered_historical_models[to_model.__name__] from_hist_model = registered_historical_models[from_model.__name__] attrs = { u'__module__': from_model.__module__, 'history_id': models.AutoField(primary_key=True), from_hist_model.__name__: models.ForeignKey(to=from_hist_model, related_name='+'), to_hist_model.__name__: models.ForeignKey(to=to_hist_model, related_name='+'), '__str__': lambda self: '%s' % self.__name__ } name = '{}_{}_fake'.format(from_hist_model.__name__, to_hist_model.__name__) historical_model = python_2_unicode_compatible(type(str(name), self.bases, attrs)) fake_m2m_models[(from_model, historical_model, from_name)] = (to_model, historical_model, to_name)
def create_history_model(self, model): """ Creates a historical model to associate with the model provided. """ attrs = {'__module__': self.module} app_module = models.get_app(model._meta.app_label) if model.__module__ != self.module: # registered under different app attrs['__module__'] = self.module elif app_module.__name__ != self.module: # has meta options with app_label attrs['__module__'] = app_module.__name__ fields = self.copy_fields(model) attrs.update(fields) attrs.update(self.get_extra_fields(model, fields)) # type in python2 wants str as a first argument attrs.update(Meta=type(str('Meta'), (), self.get_meta_options(model))) name = 'Historical%s' % model._meta.object_name registered_models[model._meta.db_table] = model return python_2_unicode_compatible(type(str(name), (models.Model,), attrs))
def create_history_model(self, model): """ Creates a historical model to associate with the model provided. """ attrs = {'__module__': self.module} app_module = '%s.models' % model._meta.app_label if model.__module__ != self.module: # registered under different app attrs['__module__'] = self.module elif app_module != self.module: # has meta options with app_label app = models.get_app(model._meta.app_label) attrs['__module__'] = app.__name__ # full dotted name fields = self.copy_fields(model) attrs.update(fields) attrs.update(self.get_extra_fields(model, fields)) # type in python2 wants str as a first argument attrs.update(Meta=type(str('Meta'), (), self.get_meta_options(model))) name = 'Historical%s' % model._meta.object_name registered_models[model._meta.db_table] = model return python_2_unicode_compatible( type(str(name), (models.Model, ), attrs))
def create_history_model(self, model, inherited): """ Creates a historical model to associate with the model provided. """ attrs = { "__module__": self.module, "_history_excluded_fields": self.excluded_fields, } app_module = "%s.models" % model._meta.app_label if inherited: # inherited use models module attrs["__module__"] = model.__module__ elif model.__module__ != self.module: # registered under different app attrs["__module__"] = self.module elif app_module != self.module: # Abuse an internal API because the app registry is loading. app = apps.app_configs[model._meta.app_label] models_module = app.name attrs["__module__"] = models_module fields = self.copy_fields(model) attrs.update(fields) attrs.update(self.get_extra_fields(model, fields)) # type in python2 wants str as a first argument attrs.update(Meta=type(str("Meta"), (), self.get_meta_options(model))) if self.table_name is not None: attrs["Meta"].db_table = self.table_name # Set as the default then check for overrides name = self.get_history_model_name(model) registered_models[model._meta.db_table] = model return python_2_unicode_compatible(type(str(name), self.bases, attrs))
def _create_content_base(cls): """ This is purely an internal method. Here, we create a base class for the concrete content types, which are built in ``create_content_type``. The three fields added to build a concrete content type class/model are ``parent``, ``region`` and ``ordering``. """ # We need a template, because of the possibility of restricting # content types to a subset of all available regions. Each region # object carries a list of all allowed content types around. # Content types created before a region is initialized would not be # available in the respective region; we avoid this problem by # raising an ImproperlyConfigured exception early. cls._needs_templates() class Meta: abstract = True app_label = cls._meta.app_label ordering = ['ordering'] def __str__(self): return ( '%s<pk=%s, parent=%s<pk=%s, %s>, region=%s,' ' ordering=%d>') % ( self.__class__.__name__, self.pk, self.parent.__class__.__name__, self.parent.pk, self.parent, self.region, self.ordering) def render(self, **kwargs): """ Default render implementation, tries to call a method named after the region key before giving up. You'll probably override the render method itself most of the time instead of adding region-specific render methods. """ render_fn = getattr(self, 'render_%s' % self.region, None) if render_fn: return render_fn(**kwargs) raise NotImplementedError def get_queryset(cls, filter_args): return cls.objects.select_related().filter(filter_args) attrs = { # The basic content type is put into # the same module as the CMS base type. # If an app_label is not given, Django # needs to know where a model comes # from, therefore we ensure that the # module is always known. '__module__': cls.__module__, '__str__': __str__, 'render': render, 'get_queryset': classmethod(get_queryset), 'Meta': Meta, 'parent': models.ForeignKey(cls, related_name='%(class)s_set'), 'region': models.CharField(max_length=255), 'ordering': models.IntegerField(_('ordering'), default=0), } # create content base type and save reference on CMS class name = '_Internal%sContentTypeBase' % cls.__name__ if hasattr(sys.modules[cls.__module__], name): warnings.warn( 'The class %s.%s has the same name as the class that ' 'FeinCMS auto-generates based on %s.%s. To avoid database' 'errors and import clashes, rename one of these classes.' % (cls.__module__, name, cls.__module__, cls.__name__), RuntimeWarning) cls._feincms_content_model = python_2_unicode_compatible( type(str(name), (models.Model,), attrs)) # list of concrete content types cls._feincms_content_types = [] # list of concrete content types having methods which may be called # before or after rendering the content: # # def process(self, request, **kwargs): # May return a response early to short-circuit the # request-response cycle # # def finalize(self, request, response) # May modify the response or replace it entirely by returning # a new one # cls._feincms_content_types_with_process = [] cls._feincms_content_types_with_finalize = [] # list of item editor context processors, will be extended by # content types if hasattr(cls, 'feincms_item_editor_context_processors'): cls.feincms_item_editor_context_processors = list( cls.feincms_item_editor_context_processors) else: cls.feincms_item_editor_context_processors = [] # list of templates which should be included in the item editor, # will be extended by content types if hasattr(cls, 'feincms_item_editor_includes'): cls.feincms_item_editor_includes = dict( cls.feincms_item_editor_includes) else: cls.feincms_item_editor_includes = {}
from django.db import models try: from django.utils.encoding import python_2_unicode_compatible except ImportError: # Django < 1.5 python_2_unicode_compatible = None class Manufacturer(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name if python_2_unicode_compatible: Manufacturer = python_2_unicode_compatible(Manufacturer) else: Manufacturer.__unicode__ = Manufacturer.__str__ del Manufacturer.__str__ class Car(models.Model): manufacturer = models.ForeignKey(Manufacturer) name = models.CharField(max_length=255) def get_display_name(self): return self.name.upper()
objects = for_user.ForUserManager() @classmethod def for_user(cls, user, **kwargs): if user.is_superuser: return Q() if user.has_perm("app.see_client_regions"): return Q(client__region__group__users=user) return Q(group__users=user) def __str__(self): return self.name class Group(models.Model): name = models.CharField(max_length=100) region = models.ForeignKey(Region) users = models.ManyToManyField(settings.AUTH_USER_MODEL) objects = for_user.ForUserManager() @classmethod def for_user(cls, user, **kwargs): if user.has_perm("app.see_all_groups"): return Q() return Q(users=user) def __str__(self): return self.name Group = python_2_unicode_compatible(Group)
@classmethod def for_user(cls, user, **kwargs): if user.is_superuser: return Q() if user.has_perm("app.see_client_regions"): return Q(client__region__group__users=user) return Q(group__users=user) def __str__(self): return self.name class Group(models.Model): name = models.CharField(max_length=100) region = models.ForeignKey(Region) users = models.ManyToManyField(settings.AUTH_USER_MODEL) objects = for_user.ForUserManager() @classmethod def for_user(cls, user, **kwargs): if user.has_perm("app.see_all_groups"): return Q() return Q(users=user) def __str__(self): return self.name Group = python_2_unicode_compatible(Group)
def __str__(self): return ugettext('%s tags') % (self.app_config.get_app_title(), ) @receiver(post_save, dispatch_uid='article_update_search_data') def update_search_data(sender, instance, **kwargs): """ Upon detecting changes in a plugin used in an Article's content (PlaceholderField), update the article's search_index so that we can perform simple searches even without Haystack, etc. """ is_cms_plugin = issubclass(instance.__class__, CMSPlugin) if Article.update_search_on_save and is_cms_plugin: placeholder = (getattr(instance, '_placeholder_cache', None) or instance.placeholder) if hasattr(placeholder, '_attached_model_cache'): if placeholder._attached_model_cache == Article: article = placeholder._attached_model_cache.objects.language( instance.language).get(content=placeholder.pk) article.search_data = article.get_search_data( instance.language) article.save() if ENABLE_REVERSION: from aldryn_reversion.core import version_controlled_content Article = version_controlled_content(Article, follow=['app_config']) Article = python_2_unicode_compatible(Article)