예제 #1
0
파일: import_mt.py 프로젝트: markpasc/bee
 def add_to_class(cls, name, value):
     # Auto-specify a field's db_column with the table name on the front.
     if isinstance(value, models.Field):
         db_column_parts = [cls.__name__.lower(), value.db_column or name]
         if isinstance(value, models.ForeignKey):
             db_column_parts.append('id')
         value.db_column = '_'.join(db_column_parts)
     ModelBase.add_to_class(cls, name, value)
예제 #2
0
def create_translations_model(model, related_name, meta, **fields):
    """
    Create the translations model for the shared model 'model'.
    'related_name' is the related name for the reverse FK from the translations
    model.
    'meta' is a (optional) dictionary of attributes for the translations model's
    inner Meta class.
    'fields' is a dictionary of fields to put on the translations model.
    
    Two fields are enforced on the translations model:
    
        language_code: A 15 char, db indexed field.
        master: A ForeignKey back to the shared model.
        
    Those two fields are unique together, this get's enforced in the inner Meta
    class of the translations table
    """
    if not meta:
        meta = {}
    unique = [('language_code', 'master')]
    meta['unique_together'] = list(meta.get('unique_together', [])) + unique
    # Create inner Meta class
    Meta = type('Meta', (object, ), meta)
    if not hasattr(Meta, 'db_table'):
        Meta.db_table = model._meta.db_table + '%stranslation' % getattr(
            settings, 'NANI_TABLE_NAME_SEPARATOR', '_')
    Meta.app_label = model._meta.app_label
    name = '%sTranslation' % model.__name__
    attrs = {}
    attrs.update(fields)
    attrs['Meta'] = Meta
    attrs['__module__'] = model.__module__
    attrs['objects'] = TranslationsModelManager()
    attrs['language_code'] = models.CharField(max_length=15, db_index=True)
    # null=True is so we can prevent cascade deletion
    attrs['master'] = models.ForeignKey(model,
                                        related_name=related_name,
                                        editable=False,
                                        null=True)
    # Create and return the new model
    translations_model = ModelBase(name, (BaseTranslationModel, ), attrs)
    bases = (
        model.DoesNotExist,
        translations_model.DoesNotExist,
    )
    DNE = type('DoesNotExist', bases, {})
    translations_model.DoesNotExist = DNE
    opts = translations_model._meta
    opts.shared_model = model

    # Register it as a global in the shared model's module.
    # This is needed so that Translation model instances, and objects which
    # refer to them, can be properly pickled and unpickled. The Django session
    # and caching frameworks, in particular, depend on this behaviour.
    mod = sys.modules[model.__module__]
    setattr(mod, name, translations_model)

    return translations_model
예제 #3
0
    def create_translations_model(self, model, related_name):
        """ Create the translations model for a shared model.
            model -- the model class to create translations for
            related_name -- the related name for the reverse FK from the translations model.
        """
        model_name = '%sTranslation' % model.__name__
        translation_bases, translation_base_fields = self._scan_model_bases(
            model)

        attrs = self.fields.copy()
        attrs.update({
            'Meta':
            self._build_meta_class(
                model,
                translation_base_fields.union(self.fields).union(
                    ('language_code', ))),
            '__module__':
            model.__module__,
        })

        if not model._meta.abstract:
            attrs.update({
                # If this class is abstract, we must not contribute management fields
                'objects':
                TranslationsModelManager(),
                'language_code':
                models.CharField(max_length=15, db_index=True),
                # Nullable so we can prevent cascade deletion
                'master':
                models.ForeignKey(model,
                                  related_name=related_name,
                                  editable=False,
                                  null=True,
                                  on_delete=models.CASCADE),
            })

        # Create the new model
        if self.base_class:
            translation_bases.insert(0, self.base_class)
        translations_model = ModelBase(model_name, tuple(translation_bases),
                                       attrs)
        translations_model._meta.shared_model = model
        if not model._meta.abstract:
            # Abstract models do not have a DNE class
            bases = (
                model.DoesNotExist,
                translations_model.DoesNotExist,
            )
            translations_model.DoesNotExist = type('DoesNotExist', bases, {})

        # Register it as a global in the shared model's module.
        # This is needed so that Translation model instances, and objects which
        # refer to them, can be properly pickled and unpickled. The Django session
        # and caching frameworks, in particular, depend on this behaviour.
        setattr(sys.modules[model.__module__], model_name, translations_model)
        return translations_model
예제 #4
0
def create_translations_model(model, related_name, meta, **fields):
    """
    Create the translations model for the shared model 'model'.
    'related_name' is the related name for the reverse FK from the translations
    model.
    'meta' is a (optional) dictionary of attributes for the translations model's
    inner Meta class.
    'fields' is a dictionary of fields to put on the translations model.
    
    Two fields are enforced on the translations model:
    
        language_code: A 15 char, db indexed field.
        master: A ForeignKey back to the shared model.
        
    Those two fields are unique together, this get's enforced in the inner Meta
    class of the translations table
    """
    if not meta:
        meta = {}
    unique = [('language_code', 'master')]
    meta['unique_together'] = list(meta.get('unique_together', [])) + unique
    # Create inner Meta class 
    Meta = type('Meta', (object,), meta)
    if not hasattr(Meta, 'db_table'):
        Meta.db_table = model._meta.db_table + '%stranslation' % getattr(settings, 'NANI_TABLE_NAME_SEPARATOR', '_')
    Meta.app_label = model._meta.app_label
    name = '%sTranslation' % model.__name__
    attrs = {}
    attrs.update(fields)
    attrs['Meta'] = Meta
    attrs['__module__'] = model.__module__
    attrs['objects'] = TranslationsModelManager()
    attrs['language_code'] = models.CharField(max_length=15, db_index=True)
    # null=True is so we can prevent cascade deletion
    attrs['master'] = models.ForeignKey(model, related_name=related_name,
                                        editable=False, null=True)
    # Create and return the new model
    translations_model = ModelBase(name, (BaseTranslationModel,), attrs)
    bases = (model.DoesNotExist, translations_model.DoesNotExist,)
    DNE = type('DoesNotExist', bases, {})
    translations_model.DoesNotExist = DNE
    opts = translations_model._meta
    opts.shared_model = model

    # Register it as a global in the shared model's module.
    # This is needed so that Translation model instances, and objects which
    # refer to them, can be properly pickled and unpickled. The Django session
    # and caching frameworks, in particular, depend on this behaviour.
    mod = sys.modules[model.__module__]
    setattr(mod, name, translations_model)

    return translations_model
예제 #5
0
def create_translations_model(model, related_name, meta, **fields):
    """
    Create the translations model for the shared model 'model'.
    'related_name' is the related name for the reverse FK from the translations
    model.
    'meta' is a (optional) dictionary of attributes for the translations model's
    inner Meta class.
    'fields' is a dictionary of fields to put on the translations model.
    
    Two fields are enforced on the translations model:
    
        language_code: A 15 char, db indexed field.
        master: A ForeignKey back to the shared model.
        
    Those two fields are unique together, this get's enforced in the inner Meta
    class of the translations table
    """
    if not meta:
        meta = {}
    unique = [('language_code', 'master')]
    meta['unique_together'] = list(meta.get('unique_together', [])) + unique
    # Create inner Meta class
    Meta = type('Meta', (object, ), meta)
    if not hasattr(Meta, 'db_table'):
        Meta.db_table = model._meta.db_table + '%stranslation' % getattr(
            settings, 'NANI_TABLE_NAME_SEPARATOR', '_')
    name = '%sTranslation' % model.__name__
    attrs = {}
    attrs.update(fields)
    attrs['Meta'] = Meta
    attrs['__module__'] = model.__module__
    attrs['objects'] = TranslationsModelManager()
    attrs['language_code'] = models.CharField(max_length=15, db_index=True)
    # null=True is so we can prevent cascade deletion
    attrs['master'] = models.ForeignKey(model,
                                        related_name=related_name,
                                        editable=False,
                                        null=True)
    # Create and return the new model
    translations_model = ModelBase(name, (BaseTranslationModel, ), attrs)
    bases = (
        model.DoesNotExist,
        translations_model.DoesNotExist,
    )
    DNE = type('DoesNotExist', bases, {})
    translations_model.DoesNotExist = DNE
    opts = translations_model._meta
    opts.shared_model = model
    return translations_model
예제 #6
0
    def __init__(cls, class_name, bases, attrs):
        # Don't execute for Gallery itself
        if [b for b in bases if isinstance(b, GalleryBase)]:
            try:
                gallery_meta = getattr(cls, 'GalleryMeta')
            except AttributeError:
                raise GalleryMetaNotDefined('%s must define GalleryMeta.' %
                                            class_name)
            try:
                member_models = getattr(gallery_meta, 'member_models')
            except AttributeError:
                raise MemberModelsNotDefined(
                    '%s.GalleryMeta must define a list of member_models.' %
                    class_name)

            gallery_meta.gallery_class = cls
            cls._gallery_meta = gallery_meta

            membership_verbose_name = '%s Membership' % cls._meta.verbose_name
            custom_membership = getattr(gallery_meta, 'membership_class', None)

            if custom_membership:
                membership_class_name = '%sBaseMembership' % class_name
            else:
                membership_class_name = '%sMembership' % class_name

            module_name = cls.__module__
            membership_class = _create_membership_class(
                    class_name=membership_class_name,
                    verbose_name=membership_verbose_name,
                    app_label=cls._meta.app_label,
                    module_name=module_name,
                    member_models=member_models,
                    abstract=bool(custom_membership),
                    gallery_class=cls,
            )

            if custom_membership:
                cls.BaseMembership = membership_class
                module = importlib.import_module(module_name)

                class Descriptor(object):
                    def __get__(self, instance, owner):
                        return getattr(module, custom_membership)
                cls.Membership = Descriptor()
            else:
                cls.Membership = membership_class

        ModelBase.__init__(cls, class_name, bases, attrs)
예제 #7
0
    def __init__(cls, class_name, bases, attrs):
        # Don't execute for Gallery itself
        if [b for b in bases if isinstance(b, GalleryBase)]:
            try:
                gallery_meta = getattr(cls, 'GalleryMeta')
            except AttributeError:
                raise GalleryMetaNotDefined('%s must define GalleryMeta.' %
                                            class_name)
            try:
                member_models = getattr(gallery_meta, 'member_models')
            except AttributeError:
                raise MemberModelsNotDefined(
                    '%s.GalleryMeta must define a list of member_models.' %
                    class_name)

            gallery_meta.gallery_class = cls
            cls._gallery_meta = gallery_meta

            membership_verbose_name = '%s Membership' % cls._meta.verbose_name
            custom_membership = getattr(gallery_meta, 'membership_class', None)

            if custom_membership:
                membership_class_name = '%sBaseMembership' % class_name
            else:
                membership_class_name = '%sMembership' % class_name

            module_name = cls.__module__
            membership_class = _create_membership_class(
                    class_name=membership_class_name,
                    verbose_name=membership_verbose_name,
                    app_label=cls._meta.app_label,
                    module_name=module_name,
                    member_models=member_models,
                    abstract=bool(custom_membership),
                    gallery_class=cls,
            )

            if custom_membership:
                cls.BaseMembership = membership_class
                module = importlib.import_module(module_name)

                class Descriptor(object):
                    def __get__(self, instance, owner):
                        return getattr(module, custom_membership)
                cls.Membership = Descriptor()
            else:
                cls.Membership = membership_class

        ModelBase.__init__(cls, class_name, bases, attrs)
예제 #8
0
파일: models.py 프로젝트: mu-Corp/SmellGame
 def __new__(cls, *args, **kwargs):
     warnings.warn(
         'TranslatableModelBase metaclass is deprecated and will '
         'be removed. Hvad no longer uses a custom metaclass so conflict '
         'resolution is no longer required, TranslatableModelBase can be '
         'dropped.', DeprecationWarning)
     return ModelBase.__new__(cls, *args, **kwargs)
예제 #9
0
def cateapp_factory(class_s, category_name, model=Application):
    def _get_meta(category_name):
        class Meta:
            proxy = True
            app_label = string_with_title("cateapps", _("Category Apps"))
            verbose_name = category_name
            verbose_name_plural = category_name

        return Meta

    class_attrs = {
        'Meta':
        _get_meta(category_name),
        '__module__':
        __name__,
        'objects':
        CustomManager({
            'category__id': get_category(category_name, only_id=True),
            'review_status__gte': REVIEW_STATUS.APPROVED
        })
    }
    class_name = '%s%s' % (model.__name__, class_s)
    model_class = ModelBase(class_name, (model, ), class_attrs)
    create_permission(model_class)
    return model_class
예제 #10
0
    def __new__(cls, name, bases, attrs):
        """
        We must define our Typeclasses as proxies. We also store the
        path directly on the class, this is required by managers.
        """

        # storage of stats
        attrs["typename"] = name
        attrs["path"] = "%s.%s" % (attrs["__module__"], name)

        # typeclass proxy setup
        if "Meta" not in attrs:

            class Meta(object):
                proxy = True
                app_label = attrs.get("__applabel__", "typeclasses")

            attrs["Meta"] = Meta
        attrs["Meta"].proxy = True

        new_class = ModelBase.__new__(cls, name, bases, attrs)

        # attach signals
        signals.post_save.connect(call_at_first_save, sender=new_class)
        signals.pre_delete.connect(remove_attributes_on_delete,
                                   sender=new_class)
        return new_class
예제 #11
0
    def __new__(cls, name, bases, attrs):
        """
        Instantiation of the State type.

        When this type is created, also create a logging model if required.
        """
        if name != 'StateModel' and 'Machine' in attrs:
            attrs['state'] = StateField(max_length=100,
                                        default='0',
                                        verbose_name=_('state id'),
                                        machine=attrs['Machine'])

        # Wrap __unicode__ for state model
        if '__unicode__' in attrs:
            old_unicode = attrs['__unicode__']

            def new_unicode(self):
                return '%s (%s)' % (old_unicode(self),
                                    self.Machine.get_state(
                                        self.state).description)

            attrs['__unicode__'] = new_unicode

        # Call class constructor of parent
        return ModelBase.__new__(cls, name, bases, attrs)
예제 #12
0
파일: models.py 프로젝트: martymarty/sctms
    def __new__(cls, name, bases, attrs):

        # redefine the related name in the foreign key to TournamentNode,
        # so classes with the same name (from different apps) won't clash
        try:
            from tms.models import TournamentNode
        except ImportError:
            pass
        else:
            if (TournamentNode in bases and not
                ('Meta' in attrs and getattr(attrs['Meta'], 'proxy', False))):
                attrs['tournamentnode_ptr'] = models.OneToOneField(
                    TournamentNode,
                    related_name="%(app_label)s_%(class)s_related",
                    parent_link=True
                )

        # add leaf class manager to all subclasses (unless they define their own)
        if 'objects' not in attrs:
            attrs['objects'] = ThisTypeOnlyManager()

        NewNodeType = ModelBase.__new__(cls, name, bases, attrs)

        type_id = NewNodeType.get_id()

        def node_init(self, *args, **kwargs):
            # TODO: preserve custom init method?
            models.Model.__init__(self, *args, **kwargs)
            if not self.type_id:
                self.type_id = type_id

        NewNodeType.__init__ = node_init

        node_types[type_id] = NewNodeType
        return NewNodeType
예제 #13
0
def banner_factory(area,
                   cate_name=None,
                   recommend_type=None,
                   model=CategoryFoucsImage):
    def _get_meta(area, cate_name=None, recommend_type=None):
        banner_verbose_name = '%s - %s' % (BANNER_IMAGE_AREAS.get_label(area) + '', \
                cate_name if area == BANNER_IMAGE_AREAS.TOP else RECOMMEND_TYPES.get_label(recommend_type))

        class Meta:
            proxy = True
            app_label = string_with_title("banner", _("Banner Recommend"))
            verbose_name = banner_verbose_name
            verbose_name_plural = banner_verbose_name

        return Meta

    manager_cond = {'area__exact': area}
    class_name = '%s%s' % (model.__name__, BANNER_IMAGE_AREAS.get_key(area))
    if area == BANNER_IMAGE_AREAS.TOP:
        cate_id = get_category(cate_name, only_id=True)
        manager_cond.update({'category__id': cate_id})
        class_name += str(cate_id)
    else:
        manager_cond.update({'recommend_type__exact': recommend_type})
        class_name += RECOMMEND_TYPES.get_key(recommend_type)

    class_attrs = {
        'Meta': _get_meta(area, cate_name, recommend_type),
        '__module__': __name__,
        'objects': CustomManager(manager_cond)
    }
    model_class = ModelBase(class_name, (model, ), class_attrs)
    create_permission(model_class)
    return model_class
예제 #14
0
    def setUp(self):
        # Create a dummy model which extends the mixin. A RuntimeWarning will
        # occur if the model is registered twice
        if not hasattr(self, "model"):
            self.model = ModelBase(
                "__TestModel__" + self.mixin.__name__,
                (self.mixin, ),
                {"__module__": self.mixin.__module__},
            )

        # Create the schema for our test model. If the table already exists,
        # will pass
        try:
            with connection.schema_editor() as schema_editor:
                schema_editor.create_model(self.model)
        except ProgrammingError:
            pass

        yield

        # Delete the schema for the test model. If no table, will pass
        try:
            with connection.schema_editor() as schema_editor:
                schema_editor.delete_model(self.model)
        except ProgrammingError:
            pass
예제 #15
0
    def __new__(cls, name, bases, attrs):

        # whether base classes should be filtered
        cls.hide_bases = False
        # only filter bases if this wasn't invoked by the ModelMiddleware
        # class, which is a super class for all custom middleware, and the
        # one we are using as a filter key
        if not (name == 'ModelMiddleware'):
            if not (ModelMiddleware in bases):
                cls.hide_bases = True
        if cls.hide_bases:
            # replace the original bases with filtered ones to fool Django's inheritance
            bases = _filter_bases(bases, ModelMiddleware)
        # set the middleware options under Klass._middle
        if attrs.has_key('Middle'):
            midopts = attrs['Middle']
            assert type(
                midopts
            ) == types.ClassType, "Middle attribute of %s model must be a class, not a %s object" % (
                name, type(midopts))
            opts = {}
            opts.update([(k, v) for k, v in midopts.__dict__.items()
                         if not k.startswith('_')])
            attrs["_middle"] = opts
            attrs.pop('Middle')
        return ModelBase.__new__(cls, name, bases, attrs)
예제 #16
0
        def __new__(mcs, name, bases, attrs):

            new_unicode = ""
            if "__str__" in attrs:
                old_unicode = attrs["__str__"]

                def new_unicode(self):
                    """New Unicode"""
                    return "{} ({})".format(
                        old_unicode(self), self.get_state_info().description
                    )

            attrs["__str__"] = new_unicode

            attrs["__module__"] = state_model.__module__
            values = {
                "model_name": state_model.__name__,
                "field_name": field_name.capitalize(),
            }
            class_name = conf.LOG_MODEL_NAME.format(**values)

            # Make sure that for Python2, class_name is a 'str' object.
            # In Django 1.7, `field_name` returns a unicode object, causing
            # `class_name` to be unicode as well.
            if sys.version_info[0] == 2:
                class_name = str(class_name)

            return ModelBase.__new__(mcs, class_name, bases, attrs)
예제 #17
0
    def __new__(mcs, name, bases, attrs):
        """
        Instantiation of the State type.

        When this type is created, also create a logging model if required.
        """
        if name != "StateModel" and "Machine" in attrs:
            attrs["state"] = StateField(
                max_length=100,
                default="0",
                verbose_name=_("state id"),
                machine=attrs["Machine"],
            )

        # Wrap __unicode__ for state model
        if "__str__" in attrs:
            old_unicode = attrs["__str__"]

            def new_unicode(self):
                return "{} ({})".format(
                    old_unicode(self),
                    self.Machine.get_state(self.state).description)

            attrs["__str__"] = new_unicode

        # Call class constructor of parent
        return ModelBase.__new__(mcs, name, bases, attrs)
예제 #18
0
파일: log.py 프로젝트: TaurusCanis/tcr_home
        def __new__(c, name, bases, attrs):

            new_unicode = u''
            if '__unicode__' in attrs:
                old_unicode = attrs['__unicode__']

                def new_unicode(self):
                    """New Unicode"""
                    return u'%s (%s)' % (old_unicode(self),
                                         self.get_state_info().description)

            attrs['__unicode__'] = new_unicode

            attrs['__module__'] = state_model.__module__
            values = {
                'model_name': state_model.__name__,
                'field_name': field_name.capitalize()
            }
            class_name = conf.LOG_MODEL_NAME % values

            # Make sure that for Python2, class_name is a 'str' object.
            # In Django 1.7, `field_name` returns a unicode object, causing
            # `class_name` to be unicode as well.
            if sys.version_info[0] == 2:
                class_name = str(class_name)

            return ModelBase.__new__(c, class_name, bases, attrs)
예제 #19
0
 def build_model(cls, ensure_slug_unicity_bool, handle_redirection_bool):
     model_name = f'{cls.__name__}_{cls.mixin.__name__}_{ensure_slug_unicity_bool}_{handle_redirection_bool}'
     attributes = {
         '__module__':
         'stack_it',
         'field':
         models.CharField("Test Field", max_length=50),
         'parent':
         models.ForeignKey('self',
                           related_name='children',
                           on_delete=models.CASCADE,
                           null=True),
         'get_children':
         lambda x: x.children.all(),
         'SLUGIFY_FROM':
         'field',
         'TREE_PARENT_FIELD':
         'parent',
         'ENSURE_SLUG_UNICITY_BOOL':
         ensure_slug_unicity_bool,
         'HANDLE_REDIRECTION_BOOL':
         handle_redirection_bool
     }
     model = ModelBase(model_name, (cls.mixin, ), attributes)
     translator.register(model, InternationalSlugMixinTranslation)
     with connection.schema_editor() as schema_editor:
         schema_editor.create_model(model)
     return model
예제 #20
0
    def setUp(self):
        from django.db import connection
        from django.db.models.base import ModelBase
        from django.core.management.color import no_style
        from django_sphinxsearch.managers import SearchManager

        # Create a dummy model which extends the mixin
        import pudb
        pudb.set_trace()
        self.model = ModelBase('__TestModel__{}'.format(self.mixin.__name__),
                               (self.mixin, ),
                               {'__module__': self.mixin.__module__})
        # Create the schema for our test model
        self._style = no_style()
        sql, _ = connection.creation.sql_create_model(self.model, self._style)
        self._cursor = connection.cursor()
        for statement in sql:
            self._cursor.execute(statement)

        self.model.search = SearchManager(index="test_index",
                                          fields={'data': 100},
                                          limit=10)
        self.model.search.contribute_to_class(model=self.model, name="search")

        source_data = (
            "Python is a programming language that lets you work more quickly and integrate your systems more effectively.",
            "You can learn to use Python and see almost immediate gains in productivity and lower maintenance costs.",
            "Python runs on Windows, Linux/Unix, Mac OS X, and has been ported to the Java and .NET virtual machines.",
            "Python is free to use, even for commercial products, because of its OSI-approved open source license.",
            "New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3.",
            "The Python Software Foundation holds the intellectual property rights behind Python, underwrites the PyCon conference, and funds other projects in the Python community."
        )
        for pk, data in enumerate(source_data, start=1):
            instance = self.model(pk=pk, data=data)
            instance.save()
예제 #21
0
def applistitem_factory(class_s, app_list, model=AppListItem):
    def _get_meta(app_list):
        if app_list.list_type == APP_LIST_TYPES.BANNER:

            class Meta:
                proxy = True
                app_label = string_with_title("banner", _("Banner Recommend"))
                verbose_name = app_list.name
                verbose_name_plural = app_list.name
        else:

            class Meta:
                proxy = True
                app_label = string_with_title("applist", _("AppList"))
                verbose_name = app_list.name
                verbose_name_plural = app_list.name

        return Meta

    objects = CustomManager({'app_list': app_list})
    class_attrs = {
        'Meta': _get_meta(app_list),
        '__module__': __name__,
        'objects': objects
    }
    if app_list.list_type == APP_LIST_TYPES.BANNER:
        class_name = 'Banner%s%s' % (model.__name__, class_s)
    else:
        class_name = '%s%s' % (model.__name__, class_s)
    model_class = ModelBase(class_name, (model, ), class_attrs)
    create_permission(model_class)
    return model_class
예제 #22
0
def catearticle_factory(class_s, category_name, model=Article):
    def _get_meta(category_name):
        class Meta:
            proxy = True
            app_label = StringWithTitle('catearticles', _('Category Articles'))
            verbose_name = category_name
            verbose_name_plural = category_name

        return Meta

    class_attrs = {
        'Meta':
        _get_meta(category_name),
        '__module__':
        __name__,
        'objects':
        BaseManager({
            'category__id__in':
            get_category(category_name).get_children(only_id=True)
        })
    }
    class_name = '%s%s' % (model.__name__, class_s)
    model_class = ModelBase(class_name, (model, ), class_attrs)
    create_permission(model_class)
    return model_class
예제 #23
0
    def create_translations_model(self, model, related_name):
        """ Create the translations model for a shared model.
            model -- the model class to create translations for
            related_name -- the related name for the reverse FK from the translations model.
        """
        model_name = "%sTranslation" % model.__name__
        translation_bases, translation_base_fields = self._scan_model_bases(model)

        attrs = self.fields.copy()
        attrs.update(
            {
                "Meta": self._build_meta_class(
                    model, translation_base_fields.union(self.fields).union(("language_code",))
                ),
                "__module__": model.__module__,
            }
        )

        if not model._meta.abstract:
            attrs.update(
                {
                    # If this class is abstract, we must not contribute management fields
                    "objects": TranslationsModelManager(),
                    "language_code": models.CharField(max_length=15, db_index=True),
                    # Nullable so we can prevent cascade deletion
                    "master": models.ForeignKey(
                        model, related_name=related_name, editable=False, null=True, on_delete=models.CASCADE
                    ),
                }
            )

        # Create the new model
        if self.base_class:
            translation_bases.insert(0, self.base_class)
        translations_model = ModelBase(model_name, tuple(translation_bases), attrs)
        translations_model._meta.shared_model = model
        if not model._meta.abstract:
            # Abstract models do not have a DNE class
            bases = (model.DoesNotExist, translations_model.DoesNotExist)
            translations_model.DoesNotExist = type("DoesNotExist", bases, {})

        # Register it as a global in the shared model's module.
        # This is needed so that Translation model instances, and objects which
        # refer to them, can be properly pickled and unpickled. The Django session
        # and caching frameworks, in particular, depend on this behaviour.
        setattr(sys.modules[model.__module__], model_name, translations_model)
        return translations_model
예제 #24
0
    def __new__(cls, name, bases, attrs):

        bases = list(bases)
        new_class = ModelBase.__new__(cls, name, tuple(bases), attrs)
        if new_class._meta.abstract:
            pass

        return new_class
예제 #25
0
 def __new__(cls, name, bases, attrs):
     # inject PageBase fields
     for k, v in cls.base_fields.items():
         if k not in attrs:
             attrs[k] = cls.base_fields[k]
     page_cls = ModelBase.__new__(cls, name, bases, attrs)
     register(page_cls)
     return page_cls
예제 #26
0
 def __new__(cls, name, bases, attrs):
     # inject Profile fields
     for k, v in cls.base_fields.items():
         if k not in attrs:
             attrs[k] = cls.base_fields[k]
     model = ModelBase.__new__(cls, name, bases, attrs)
     _profiles.append(model)
     return model
예제 #27
0
    def setUpClass(cls):
        cls.model = ModelBase('__TestModel__' + cls.model.__name__,
                              (cls.model, ),
                              {'__module__': cls.model.__module__})

        with connection.schema_editor() as schema_editor:
            schema_editor.create_model(cls.model)
        super(ModelMixinTestCase, cls).setUpClass()
예제 #28
0
    def __new__(cls, name, bases, attrs):

        bases = list(bases)
        new_class = ModelBase.__new__(cls, name, tuple(bases), attrs)
        if new_class._meta.abstract:
            pass

        return new_class
예제 #29
0
 def __new__(cls, name, bases, attrs):
     # inject PageBase fields
     for k, v in cls.base_fields.items():
         if k not in attrs:
             attrs[k] = cls.base_fields[k]
     page_cls = ModelBase.__new__(cls, name, bases, attrs)
     register(page_cls)
     return page_cls
예제 #30
0
 def setUpClass(cls):
     # # Create a dummy model which extends the mixin
     cls.Model = ModelBase('__TestModel__' + cls.mixins[0].__name__,
                           cls.mixins,
                           {'__module__': cls.mixins[0].__module__})
     # Create the schema for our test model
     with connection.schema_editor() as schema_editor:
         schema_editor.create_model(cls.Model)
     super().setUpClass()
예제 #31
0
    def __new__(cls, name, bases, attrs):
        new_class = ModelBase.__new__(cls, name, bases, attrs)
        if hasattr(new_class, 'FreeAdmin'):
            new_class.add_to_class('_admin',
                 FreeAdminWrapper(new_class.FreeAdmin))
        else:
            new_class.add_to_class('_admin', FreeAdminWrapper())

        return new_class
예제 #32
0
    def setUp(self):
        # Create a dummy model which extends the mixin
        self.model = ModelBase('__TestModel__' + self.mixin.__name__,
                               (self.mixin, ),
                               {'__module__': self.mixin.__module__})

        # Create the database schema for our test model
        with connection.schema_editor() as schema_editor:
            schema_editor.create_model(self.model)
    def setUp(self):
        # Create a dummy model
        self.model = ModelBase('__TestModel__' + self.model.__name__,
                               (self.model, ),
                               {'__module__': self.model.__module__})

        # Create the schema for our test model
        with connection.schema_editor() as schema_editor:
            schema_editor.create_model(self.model)
예제 #34
0
    def setUpClass(cls):
        # Create a dummy model
        cls.model = ModelBase(
            '__TestModel__' + cls.model.__name__, (cls.model,),
            {'__module__': cls.model.__module__}
        )

        # Create the schema for our test model
        with connection.schema_editor() as schema_editor:
            schema_editor.create_model(cls.model)
예제 #35
0
            def __new__(c, name, bases, attrs):
                # Rename class
                name = '%sVoteSummary' % model._meta.object_name

                # This attribute is required for a model to function properly in Django.
                attrs['__module__'] = model.__module__

                vote_summary_model = ModelBase.__new__(c, name, bases, attrs)

                return vote_summary_model
예제 #36
0
    def __new__(cls, name, bases, attrs):
        from freenasUI.freeadmin.site import site

        new_class = ModelBase.__new__(cls, name, bases, attrs)
        if new_class._meta.abstract:
            pass
        elif hasattr(new_class, 'FreeAdmin'):
            site.register(new_class, freeadmin=new_class.FreeAdmin)

        return new_class
예제 #37
0
    def setUp(self):
        """Create a dummy model which extends the mixin"""
        self.model = ModelBase(
            '__TestModel__' + self.mixin.__name__,
            (self.mixin,),
            {'__module__': self.mixin.__module__}
        )

        with connection.schema_editor() as schema_editor:
            schema_editor.create_model(self.model)
예제 #38
0
    def __new__(cls, name, bases, attrs):
        from freenasUI.freeadmin.site import site

        new_class = ModelBase.__new__(cls, name, bases, attrs)
        if new_class._meta.abstract:
            pass
        elif hasattr(new_class, 'FreeAdmin'):
            site.register(new_class, freeadmin=new_class.FreeAdmin)

        return new_class
예제 #39
0
    def __new__(cls, name, bases, attrs):
        super_new = ModelBase.__new__(cls, name, bases, attrs)
        module_name = camel_to_underscore(name)
        model_module = sys.modules[cls.__module__]

        app_label = super_new.__module__.split('.')[-2]
        db_table = '%s_%s' % (app_label, module_name)
        if not getattr(super_new._meta, 'proxy', False):
            super_new._meta.db_table = db_table

        return super_new