Esempio n. 1
0
def test_getattr_path_and_setattr_path():
    class Baz(object):
        def __init__(self):
            self.quux = 3

    class Bar(object):
        def __init__(self):
            self.baz = Baz()

    class Foo(object):
        def __init__(self):
            self.bar = Bar()

    foo = Foo()
    assert getattr_path(foo, 'bar__baz__quux') == 3

    setattr_path(foo, 'bar__baz__quux', 7)

    assert getattr_path(foo, 'bar__baz__quux') == 7

    setattr_path(foo, 'bar__baz', None)
    assert getattr_path(foo, 'bar__baz__quux') is None

    setattr_path(foo, 'bar', None)
    assert foo.bar is None
Esempio n. 2
0
def test_setattr_path():
    assert getattr_path(setattr_path(Struct(a=0), 'a', 1), 'a') == 1
    assert getattr_path(setattr_path(Struct(a=Struct(b=0)), 'a__b', 2),
                        'a__b') == 2

    with pytest.raises(AttributeError):
        setattr_path(Struct(a=1), 'a__b', 1)
Esempio n. 3
0
def test_getattr_path():
    assert getattr_path(Struct(a=1), 'a') == 1
    assert getattr_path(Struct(a=Struct(b=2)), 'a__b') == 2
    with pytest.raises(AttributeError):
        getattr_path(Struct(a=2), 'b')

    assert getattr_path(Struct(a=None), 'a__b__c__d') is None
Esempio n. 4
0
def test_getattr_path_and_setattr_path():
    class Baz(object):
        def __init__(self):
            self.quux = 3

    class Bar(object):
        def __init__(self):
            self.baz = Baz()

    class Foo(object):
        def __init__(self):
            self.bar = Bar()

    foo = Foo()
    assert 3 == getattr_path(foo, 'bar__baz__quux')

    setattr_path(foo, 'bar__baz__quux', 7)

    assert 7 == getattr_path(foo, 'bar__baz__quux')

    setattr_path(foo, 'bar__baz', None)
    assert None is getattr_path(foo, 'bar__baz__quux')

    setattr_path(foo, 'bar', None)
    assert None is foo.bar
Esempio n. 5
0
def test_getattr_path_and_setattr_path():
    class Baz(object):
        def __init__(self):
            self.quux = 3

    class Bar(object):
        def __init__(self):
            self.baz = Baz()

    class Foo(object):
        def __init__(self):
            self.bar = Bar()

    foo = Foo()
    assert 3 == getattr_path(foo, 'bar__baz__quux')

    setattr_path(foo, 'bar__baz__quux', 7)

    assert 7 == getattr_path(foo, 'bar__baz__quux')

    setattr_path(foo, 'bar__baz', None)
    assert None is getattr_path(foo, 'bar__baz__quux')

    setattr_path(foo, 'bar', None)
    assert None is foo.bar
Esempio n. 6
0
def test_getattr_path():
    assert getattr_path(Struct(a=1), 'a') == 1
    assert getattr_path(Struct(a=Struct(b=2)), 'a__b') == 2
    with pytest.raises(AttributeError):
        getattr_path(Struct(a=2), 'b')

    assert getattr_path(Struct(a=None), 'a__b__c__d') is None
Esempio n. 7
0
def many_to_many_factory(model_field, **kwargs):
    setdefaults_path(
        kwargs,
        choices=model_field.rel.to.objects.all(),
        read_from_instance=lambda field, instance: getattr_path(instance, field.attr).all(),
        extra__django_related_field=True,
    )
    kwargs['model'] = model_field.rel.to
    return Field.multi_choice_queryset(**kwargs)
Esempio n. 8
0
def many_to_many_factory(model_field, **kwargs):
    setdefaults_path(
        kwargs,
        choices=model_field.rel.to.objects.all(),
        read_from_instance=lambda field, instance: getattr_path(instance, field.attr).all(),
        extra__django_related_field=True,
    )
    kwargs['model'] = model_field.rel.to
    return Field.multi_choice_queryset(**kwargs)
Esempio n. 9
0
def order_by_on_list(objects, order_field, is_desc=False):
    """
    Utility function to sort objects django-style even for non-query set collections

    :param objects: list of objects to sort
    :param order_field: field name, follows django conventions, so "foo__bar" means `foo.bar`, can be a callable.
    :param is_desc: reverse the sorting
    :return:
    """
    if callable(order_field):
        objects.sort(key=order_field, reverse=is_desc)
        return

    objects.sort(key=lambda x: getattr_path(x, order_field), reverse=is_desc)
Esempio n. 10
0
    def __init__(self, request=None, data=None, instance=None, fields=None, model=None, post_validation=None):
        """
        :type fields: list of Field
        :type data: dict[basestring, basestring]
        :type model: django.db.models.Model
        """
        self.request = request
        if data is None and request:
            data = request.POST if request.method == 'POST' else request.GET

        if isinstance(fields, dict):  # Declarative case
            fields = [merged(field, dict(name=name)) for name, field in fields.items()]
        self.fields = sort_after([BoundField(field, self) for field in fields])

        if instance is not None:
            for field in self.fields:
                if field.attr:
                    initial = getattr_path(instance, field.attr)
                    if field.is_list:
                        field.initial_list = initial
                    else:
                        field.initial = initial

        if data:
            for field in self.fields:
                if field.is_list:
                    try:
                        # noinspection PyUnresolvedReferences
                        raw_data_list = data.getlist(field.name)
                    except AttributeError:  # pragma: no cover
                        raw_data_list = data.get(field.name)
                    if raw_data_list and field.strip_input:
                        raw_data_list = [x.strip() for x in raw_data_list]
                    if raw_data_list is not None:
                        field.raw_data_list = raw_data_list
                else:
                    field.raw_data = data.get(field.name)
                    if field.raw_data and field.strip_input:
                        field.raw_data = field.raw_data.strip()

        if post_validation is not None:
            self.post_validation = post_validation
        self.fields_by_name = {field.name: field for field in self.fields}
        self.style = None
        self.model = model
        self._valid = None
        self.errors = []
        self.should_parse = bool(data)
        self.evaluate()
        self.is_valid()
Esempio n. 11
0
def order_by_on_list(objects, order_field, is_desc=False):
    """
    Utility function to sort objects django-style even for non-query set collections

    :param objects: list of objects to sort
    :param order_field: field name, follows django conventions, so "foo__bar" means `foo.bar`, can be a callable.
    :param is_desc: reverse the sorting
    :return:
    """
    if callable(order_field):
        objects.sort(key=order_field, reverse=is_desc)
        return

    objects.sort(key=lambda x: getattr_path(x, order_field), reverse=is_desc)
Esempio n. 12
0
    def __init__(self, **kwargs):
        """
        :param name: the name of the column
        :param attr: What attribute to use, defaults to same as name. Follows django conventions to access properties of properties, so "foo__bar" is equivalent to the python code `foo.bar`. This parameter is based on the variable name of the Column if you use the declarative style of creating tables.
        :param display_name: the text of the header for this column. By default this is based on the `name` parameter so normally you won't need to specify it.
        :param css_class: CSS class of the header
        :param url: URL of the header. This should only be used if "sorting" is off.
        :param title: title/tool tip of header
        :param show: set this to False to hide the column
        :param sortable: set this to False to disable sorting on this column
        :param sort_key: string denoting what value to use as sort key when this column is selected for sorting. (Or callable when rendering a table from list.)
        :param sort_default_desc: Set to True to make table sort link to sort descending first.
        :param group: string describing the group of the header. If this parameter is used the header of the table now has two rows. Consecutive identical groups on the first level of the header are joined in a nice way.
        :param auto_rowspan: enable automatic rowspan for this column. To join two cells with rowspan, just set this auto_rowspan to True and make those two cells output the same text and we'll handle the rest.
        :param cell__template: name of a template file. The template gets arguments: `table`, `bound_column`, `bound_row`, `row` and `value`.
        :param cell__value: string or callable that receives kw arguments: `table`, `column` and `row`. This is used to extract which data to display from the object.
        :param cell__format: string or callable that receives kw arguments: `table`, `column`, `row` and `value`. This is used to convert the extracted data to html output (use `mark_safe`) or a string.
        :param cell__attrs: dict of attr name to callables that receive kw arguments: `table`, `column`, `row` and `value`.
        :param cell__url: callable that receives kw arguments: `table`, `column`, `row` and `value`.
        :param cell__url_title: callable that receives kw arguments: `table`, `column`, `row` and `value`.
        """

        kwargs.update({'attrs__class__' + c: True for c in kwargs.get('css_class', {})})

        setdefaults(kwargs, dict(
            bulk__show=False,
            query__show=False,
            extra=Struct(),
            attrs={},
            cell__template=None,
            cell__value=lambda table, column, row: getattr_path(row, evaluate(column.attr, table=table, column=column)),
            cell__format=default_cell_formatter,
            cell__attrs={},
            cell__url=None,
            cell__url_title=None
        ))
        namespaces = Struct(collect_namespaces(kwargs))
        namespaces.attrs = Struct(collect_namespaces(namespaces.attrs))
        namespaces.cell = Struct(collect_namespaces(namespaces.cell))
        namespaces.cell.attrs = Struct(collect_namespaces(namespaces.cell.attrs))

        namespaces.bulk = Struct(namespaces.bulk)
        namespaces.query = Struct(namespaces.query)
        namespaces.extra = Struct(namespaces.extra)

        setdefaults(namespaces.attrs, {'class': {}})
        setdefaults(namespaces.cell.attrs, {'class': {}})

        super(Column, self).__init__(**namespaces)
Esempio n. 13
0
def test_datetime():
    x = Column.datetime()
    assert getattr_path(x, "query__class") == Variable.datetime
    assert getattr_path(x, "bulk__class") == Field.datetime
Esempio n. 14
0
def default_read_from_instance(field, instance):
    return getattr_path(instance, field.attr)
Esempio n. 15
0
 def url(table, column, row, value):
     del table, value
     r = getattr_path(row, column.attr)
     return r.get_absolute_url() if r else ""
Esempio n. 16
0
class Column(Frozen, ColumnBase):
    @dispatch(
        bulk__show=False,
        query__show=False,
        attrs=EMPTY,
        attrs__class=EMPTY,
        cell__template=None,
        cell__attrs=EMPTY,
        cell__value=lambda table, column, row: getattr_path(
            row, evaluate(column.attr, table=table, column=column)),
        cell__format=default_cell_formatter,
        cell__url=None,
        cell__url_title=None,
    )
    def __init__(self, **kwargs):
        """
        :param name: the name of the column
        :param attr: What attribute to use, defaults to same as name. Follows django conventions to access properties of properties, so "foo__bar" is equivalent to the python code `foo.bar`. This parameter is based on the variable name of the Column if you use the declarative style of creating tables.
        :param display_name: the text of the header for this column. By default this is based on the `name` parameter so normally you won't need to specify it.
        :param css_class: CSS class of the header
        :param url: URL of the header. This should only be used if "sorting" is off.
        :param title: title/tool tip of header
        :param show: set this to False to hide the column
        :param sortable: set this to False to disable sorting on this column
        :param sort_key: string denoting what value to use as sort key when this column is selected for sorting. (Or callable when rendering a table from list.)
        :param sort_default_desc: Set to True to make table sort link to sort descending first.
        :param group: string describing the group of the header. If this parameter is used the header of the table now has two rows. Consecutive identical groups on the first level of the header are joined in a nice way.
        :param auto_rowspan: enable automatic rowspan for this column. To join two cells with rowspan, just set this auto_rowspan to True and make those two cells output the same text and we'll handle the rest.
        :param cell__template: name of a template file. The template gets arguments: `table`, `bound_column`, `bound_row`, `row` and `value`.
        :param cell__value: string or callable that receives kw arguments: `table`, `column` and `row`. This is used to extract which data to display from the object.
        :param cell__format: string or callable that receives kw arguments: `table`, `column`, `row` and `value`. This is used to convert the extracted data to html output (use `mark_safe`) or a string.
        :param cell__attrs: dict of attr name to callables that receive kw arguments: `table`, `column`, `row` and `value`.
        :param cell__url: callable that receives kw arguments: `table`, `column`, `row` and `value`.
        :param cell__url_title: callable that receives kw arguments: `table`, `column`, `row` and `value`.
        """

        setdefaults_path(
            kwargs,
            {'attrs__class__' + c: True
             for c in kwargs.get('css_class', {})})
        super(Column, self).__init__(**kwargs)

    @staticmethod
    def text(**kwargs):
        return Column(**kwargs)

    @staticmethod
    def icon(icon, is_report=False, icon_title='', show=True, **kwargs):
        """
        Shortcut to create font awesome-style icons.

        :param icon: the font awesome name of the icon
        """
        setdefaults(
            kwargs,
            dict(name='',
                 display_name='',
                 sortable=False,
                 attrs__class__thin=True,
                 show=lambda table, column: evaluate(
                     show, table=table, column=column) and not is_report,
                 title=icon_title,
                 cell__value=lambda table, column, row: True,
                 cell__attrs__class__cj=True,
                 cell__format=lambda table, column, row, value:
                 mark_safe('<i class="fa fa-lg fa-%s"%s></i>' %
                           (icon, ' title="%s"' % icon_title
                            if icon_title else '')) if value else ''))
        return Column(**kwargs)

    @staticmethod
    def edit(is_report=False, **kwargs):
        """
        Shortcut for creating a clickable edit icon. The URL defaults to `your_object.get_absolute_url() + 'edit/'`. Specify the option cell__url to override.
        """
        setdefaults(
            kwargs,
            dict(cell__url=lambda row, **_: row.get_absolute_url() + 'edit/',
                 display_name=''))
        return Column.icon('pencil-square-o', is_report, 'Edit', **kwargs)

    @staticmethod
    def delete(is_report=False, **kwargs):
        """
        Shortcut for creating a clickable delete icon. The URL defaults to `your_object.get_absolute_url() + 'delete/'`. Specify the option cell__url to override.
        """
        setdefaults(
            kwargs,
            dict(cell__url=lambda row, **_: row.get_absolute_url() + 'delete/',
                 display_name=''))
        return Column.icon('trash-o', is_report, 'Delete', **kwargs)

    @staticmethod
    def download(is_report=False, **kwargs):
        """
        Shortcut for creating a clickable download icon. The URL defaults to `your_object.get_absolute_url() + 'download/'`. Specify the option cell__url to override.
        """
        setdefaults(
            kwargs,
            dict(
                cell__url=lambda row, **_: row.get_absolute_url() +
                'download/',
                cell__value=lambda row, **_: getattr(row, 'pk', False),
            ))
        return Column.icon('download', is_report, 'Download', **kwargs)

    @staticmethod
    def run(is_report=False, show=True, **kwargs):
        """
        Shortcut for creating a clickable run icon. The URL defaults to `your_object.get_absolute_url() + 'run/'`. Specify the option cell__url to override.
        """
        setdefaults(
            kwargs,
            dict(
                name='',
                title='Run',
                sortable=False,
                css_class={'thin'},
                cell__url=lambda row, **_: row.get_absolute_url() + 'run/',
                cell__value='Run',
                show=lambda table, column: evaluate(
                    show, table=table, column=column) and not is_report,
            ))
        return Column(**kwargs)

    @staticmethod
    def select(is_report=False,
               checkbox_name='pk',
               show=True,
               checked=lambda x: False,
               **kwargs):
        """
        Shortcut for a column of checkboxes to select rows. This is useful for implementing bulk operations.

        :param checkbox_name: the name of the checkbox. Default is "pk", resulting in checkboxes like "pk_1234".
        :param checked: callable to specify if the checkbox should be checked initially. Defaults to False.
        """
        setdefaults(
            kwargs,
            dict(
                name='__select__',
                title='Select all',
                display_name=mark_safe('<i class="fa fa-check-square-o"></i>'),
                sortable=False,
                show=lambda table, column: evaluate(
                    show, table=table, column=column) and not is_report,
                attrs__class__thin=True,
                attrs__class__nopad=True,
                cell__attrs__class__cj=True,
                cell__value=lambda table, column, row: mark_safe(
                    '<input type="checkbox"%s class="checkbox" name="%s_%s" />'
                    % (' checked'
                       if checked(row.pk) else '', checkbox_name, row.pk)),
            ))
        return Column(**kwargs)

    @staticmethod
    def boolean(is_report=False, **kwargs):
        """
        Shortcut to render booleans as a check mark if true or blank if false.
        """
        def render_icon(value):
            if callable(value):
                value = value()
            return mark_safe(
                '<i class="fa fa-check" title="Yes"></i>') if value else ''

        setdefaults(
            kwargs,
            dict(
                cell__format=lambda table, column, row, value:
                yes_no_formatter(
                    table=table, column=column, row=row, value=value)
                if is_report else render_icon(value),
                cell__attrs__class__cj=True,
                query__class=Variable.boolean,
                bulk__class=Field.boolean,
            ))
        return Column(**kwargs)

    @staticmethod
    def link(**kwargs):
        """
        Shortcut for creating a cell that is a link. The URL is the result of calling `get_absolute_url()` on the object.
        """
        def url(table, column, row, value):
            del table, value
            r = getattr_path(row, column.attr)
            return r.get_absolute_url() if r else ''

        setdefaults(kwargs, dict(cell__url=url, ))
        return Column(**kwargs)

    @staticmethod
    def number(**kwargs):
        """
        Shortcut for rendering a number. Sets the "rj" (as in "right justified") CSS class on the cell and header.
        """
        setdefaults(kwargs, dict(cell__attrs__class__rj=True))
        return Column(**kwargs)

    @staticmethod
    def float(**kwargs):
        return Column.number(**kwargs)

    @staticmethod
    def integer(**kwargs):
        return Column.number(**kwargs)

    @staticmethod
    def choice_queryset(**kwargs):
        setdefaults(
            kwargs,
            dict(
                bulk__class=Field.choice_queryset,
                bulk__model=kwargs.get('model'),
                query__class=Variable.choice_queryset,
                query__model=kwargs.get('model'),
            ))
        return Column.choice(**kwargs)

    @staticmethod
    def multi_choice_queryset(**kwargs):
        setdefaults(
            kwargs,
            dict(
                bulk__class=Field.multi_choice_queryset,
                bulk__model=kwargs.get('model'),
                query__class=Variable.multi_choice_queryset,
                query__model=kwargs.get('model'),
                cell__format=lambda value, **_: ', '.join(
                    ['%s' % x for x in value.all()]),
            ))
        return Column.choice(**kwargs)

    @staticmethod
    def choice(**kwargs):
        choices = kwargs['choices']
        setdefaults(
            kwargs,
            dict(
                bulk__class=Field.choice,
                bulk__choices=choices,
                query__class=Variable.choice,
                query__choices=choices,
            ))
        return Column(**kwargs)

    @staticmethod
    def substring(**kwargs):
        setdefaults(kwargs, dict(query__gui_op=':', ))
        return Column(**kwargs)

    @staticmethod
    def date(**kwargs):
        setdefaults(
            kwargs,
            dict(
                query__gui__class=Field.date,
                query__op_to_q_op=lambda op: {
                    '=': 'exact',
                    ':': 'contains'
                }.get(op) or Q_OP_BY_OP[op],
                bulk__class=Field.date,
            ))
        return Column(**kwargs)

    @staticmethod
    def datetime(**kwargs):
        setdefaults(
            kwargs,
            dict(
                query__gui__class=Field.date,
                query__op_to_q_op=lambda op: {
                    '=': 'exact',
                    ':': 'contains'
                }.get(op) or Q_OP_BY_OP[op],
                bulk__class=Field.date,
            ))
        return Column(**kwargs)

    @staticmethod
    def email(**kwargs):
        setdefaults(
            kwargs,
            dict(bulk__class=Field.email,
                 # TODO: query__class=Variable.email,
                 ))
        return Column(**kwargs)

    @staticmethod
    def from_model(model, field_name=None, model_field=None, **kwargs):
        return member_from_model(
            model=model,
            factory_lookup=_column_factory_by_field_type,
            factory_lookup_register_function=register_column_factory,
            field_name=field_name,
            model_field=model_field,
            defaults_factory=lambda model_field: {},
            **kwargs)

    @staticmethod
    def expand_member(model, field_name=None, model_field=None, **kwargs):
        return expand_member(model=model,
                             factory_lookup=_column_factory_by_field_type,
                             field_name=field_name,
                             model_field=model_field,
                             **kwargs)
Esempio n. 17
0
 def url(table, column, row, value):
     del table, value
     r = getattr_path(row, column.attr)
     return r.get_absolute_url() if r else ''
Esempio n. 18
0
def default_read_from_instance(field, instance):
    return getattr_path(instance, field.attr)
Esempio n. 19
0
def test_email():
    x = Column.email()
    assert getattr_path(x, "query__class") == Variable.email
    assert getattr_path(x, "bulk__class") == Field.email
Esempio n. 20
0
def test_setattr_path():
    assert getattr_path(setattr_path(Struct(a=0), 'a', 1), 'a') == 1
    assert getattr_path(setattr_path(Struct(a=Struct(b=0)), 'a__b', 2), 'a__b') == 2

    with pytest.raises(AttributeError):
        setattr_path(Struct(a=1), 'a__b', 1)
Esempio n. 21
0
def test_integer():
    x = Column.integer()
    assert getattr_path(x, "query__class") == Variable.integer
    assert getattr_path(x, "bulk__class") == Field.integer
Esempio n. 22
0
def test_float():
    x = Column.float()
    assert getattr_path(x, "query__class") == Variable.float
    assert getattr_path(x, "bulk__class") == Field.float