Exemplo n.º 1
0
    def set_val(self, value):
        try:
            if self._multiple:
                value = [odm.get_by_ref(v).ref for v in value if v]
            else:
                value = odm.get_by_ref(value).ref if value else None
            super().set_val(value)
        except odm.error.InvalidReference as e:
            if not self._ignore_invalid_refs:
                raise e
        except odm.error.EntityNotFound as e:
            if not self._ignore_missing_entities:
                raise e

        return self
Exemplo n.º 2
0
    def set_val(self, value):
        """Set value of the widget.

        :param value: list[odm.model.ODMModel] | list[DBRef] | list[str]
        """

        # Single string can be received from HTML form
        if isinstance(value, str) or value is None:
            value = [value] if value else []

        if not isinstance(value, (list, tuple)):
            raise TypeError(
                "List of entities expected as a value of the widget '{}'".
                format(self.name))

        clean_val = []
        for v in value:
            if not v:
                continue

            try:
                clean_val.append(odm.get_by_ref(v).ref)
            except odm.error.InvalidReference as e:
                if not self._ignore_invalid_refs:
                    raise e
            except odm.error.EntityNotFound as e:
                if not self._ignore_missing_entities:
                    raise e

        return super().set_val(clean_val)
Exemplo n.º 3
0
    def __init__(self, uid: str, **kwargs):
        """Init
        """
        self._model = kwargs.get('model')
        if not self._model:
            raise ValueError('Model is not specified')

        self._caption_field = kwargs.get(
            'caption_field')  # type: Union[str, Callable[[odm.Entity], None]]
        if not self._caption_field:
            raise ValueError('Caption field is not specified')

        self._sort_field = kwargs.get('sort_field')  # type: str
        if not self._sort_field and isinstance(self._caption_field, str):
            self._sort_field = self._caption_field

        self._translate_captions = kwargs.get('translate_captions', False)

        self._exclude = []  # type: List[odm.model.Entity]
        for e in kwargs.get('exclude', ()):
            self._exclude.append(odm.get_by_ref(e))

        self._sort_order = kwargs.get('sort_order', odm.I_ASC)  # type: int
        self._finder_adjust = kwargs.get(
            'finder_adjust')  # type: Callable[[odm.Finder], None]
        self._ignore_missing_entities = kwargs.get('ignore_missing_entities',
                                                   False)
        self._ignore_invalid_refs = kwargs.get('ignore_invalid_refs', False)

        super().__init__(uid, **kwargs)

        # Available items will be set during call to self._get_element()
        self._items = []
Exemplo n.º 4
0
def _sanitize_kwargs_exclude(kwargs: dict):
    if not ('exclude' in kwargs and kwargs['exclude']):
        return

    if isinstance(kwargs['exclude'], odm.Entity):
        kwargs['exclude'] = [kwargs['exclude'].ref
                             ] if not kwargs['exclude'].is_new else []
    elif isinstance(kwargs['exclude'], str):
        kwargs['exclude'] = [kwargs['exclude']]
    elif isinstance(kwargs['exclude'], (list, tuple)):
        ex = []
        for item in kwargs['exclude']:
            if isinstance(item, odm.Entity):
                if not item.is_new:
                    ex.append(item.ref)
            elif isinstance(item, str):
                ex.append(item)
            else:
                raise TypeError('Unsupported type: {}'.format(type(item)))

        kwargs['exclude'] = ex

    if kwargs.get('exclude_descendants', True):
        for ref in kwargs['exclude'].copy():
            for descendant in odm.get_by_ref(ref).descendants:
                kwargs['exclude'].append(descendant.ref)
Exemplo n.º 5
0
    def create_comment(
            self,
            thread_uid: str,
            body: str,
            author: auth.model.AbstractUser,
            status: str = 'published',
            parent_uid: str = None) -> comments.model.AbstractComment:
        """Create a new comment
        """
        body = body.strip()

        comment = odm.dispense('comment')  # type: _model.ODMComment
        comment.f_set('thread_uid', thread_uid)
        comment.f_set('body', body)
        comment.f_set('author', author.uid)
        comment.f_set('status', status)
        comment.save()

        if parent_uid:
            parent = odm.get_by_ref('comment:' + parent_uid)
            if parent.depth == comments.get_comment_max_depth():
                raise RuntimeError('Comment depth is too big')

            try:
                auth.switch_user_to_system()
                parent.append_child(comment).save()
            finally:
                auth.restore_user()

        return _model.Comment(comment)
Exemplo n.º 6
0
    def set_val(self, value: Union[Iterable[odm.Entity], Iterable[str]]):
        try:
            super().set_val([odm.get_by_ref(v).ref for v in value
                             if v] if value else [])
        except odm.error.InvalidReference as e:
            if not self._ignore_invalid_refs:
                raise e
        except odm.error.EntityNotFound as e:
            if not self._ignore_missing_entities:
                raise e

        return self
Exemplo n.º 7
0
def _dispense_entity(ref: str = None, model: str = None) -> _Entity:
    # Load entity
    try:
        entity = _odm.get_by_ref(ref) if ref else _odm.dispense(model)

        if not entity:
            raise _http.error.NotFound('Entity not found')

        if not isinstance(entity, _model.HTTPAPIEntityMixin):
            raise _http.error.Forbidden("Model '{}' does not support transfer via HTTP".format(entity.model))

        return entity

    except _odm.error.ModelNotRegistered as e:
        raise _http.error.NotFound(e)
Exemplo n.º 8
0
    def __init__(self, uid: str, **kwargs):
        super().__init__(uid, **kwargs)

        self._model = kwargs.get('model')
        if not self._model:
            raise TypeError("'model' argument is not specified")

        model_cls = odm.get_model_class(self._model)
        if not (issubclass(model_cls, odm_http_api.HTTPAPIEntityMixin)
                and model_cls.odm_http_api_enabled()):
            raise TypeError(
                "Model '{}' does not support transfer via HTTP API".format(
                    self._model))

        exclude = kwargs.get('exclude', [])
        if not isinstance('exclude', (list, tuple)):
            exclude = [exclude]

        self._ignore_missing_entities = kwargs.get('ignore_missing_entities',
                                                   False)
        self._ignore_invalid_refs = kwargs.get('ignore_invalid_refs', False)
        self._sort_by = kwargs.get('sort_by')
        self._sort_order = kwargs.get('sort_order', odm.I_ASC)
        self._entity_title_field = kwargs.get('entity_title_field', 'title')
        self._entity_url_field = kwargs.get('entity_url_field', 'url')
        self._entity_thumb_field = kwargs.get('entity_thumb_field',
                                              'thumbnail')
        self._exclude = [odm.get_by_ref(v).ref for v in exclude if v]
        self._search_by = kwargs.get('search_by')
        self._search_delay = kwargs.get('search_delay', 250)
        self._search_minimum_input_length = kwargs.get(
            'search_minimum_input_length', 1)
        self._modal_title = kwargs.get('modal_title', lang.t('odm_ui@search'))
        self._modal_ok_button_caption = kwargs.get('modal_ok_button_caption',
                                                   lang.t('odm_ui@add'))
        self._empty_slot_title = kwargs.get('empty_slot_title',
                                            lang.t('odm_ui@add'))

        self._css += ' widget-odm-ui-entity-slots'
Exemplo n.º 9
0
    def _get_element(self, **kwargs):
        self._ajax_url_query.update(self._entity_title_args)

        # In AJAX-mode Select2 doesn't contain any items, but here is a selected item, it is necessary to append it
        if self._ajax_url and self._value:
            try:
                for ref in self._value if self._multiple else [self._value]:
                    entity = odm.get_by_ref(ref)
                    title = entity.odm_ui_widget_select_search_entities_title(
                        self._entity_title_args)
                    if entity.depth:
                        title = '{} {}'.format(
                            self._depth_indent * entity.depth, title)
                    self._items.append([entity.ref, title])
            except odm.error.InvalidReference as e:
                if not self._ignore_invalid_refs:
                    raise e
            except odm.error.EntityNotFound as e:
                if not self.ignore_missing_entities:
                    raise e

        return super()._get_element()