Пример #1
0
 def email(**kwargs):
     setdefaults_path(
         kwargs,
         input_type='email',
         parse=lambda string_value, **_: validate_email(string_value) or string_value,
     )
     return Field(**kwargs)
Пример #2
0
 def foreign_key_factory(model_field, **kwargs):
     setdefaults_path(
         kwargs,
         choices=model_field.foreign_related_fields[0].model.objects.all(),
         model=model_field.foreign_related_fields[0].model,
     )
     return Column.choice_queryset(model_field=model_field, **kwargs)
Пример #3
0
def foreign_key_factory(model_field, **kwargs):
    setdefaults_path(
        kwargs,
        choices=model_field.foreign_related_fields[0].model.objects.all(),
    )
    kwargs['model'] = model_field.foreign_related_fields[0].model
    return Field.choice_queryset(**kwargs)
Пример #4
0
 def email(**kwargs):
     setdefaults_path(
         kwargs,
         input_type='email',
         parse=lambda string_value, **_: validate_email(string_value) or string_value,
     )
     return Field(**kwargs)
Пример #5
0
    def datetime(**kwargs):
        iso_formats = [
            '%Y-%m-%d %H:%M:%S',
            '%Y-%m-%d %H:%M',
            '%Y-%m-%d %H',
        ]

        def datetime_parse(string_value, **_):
            errors = []
            for iso_format in iso_formats:
                try:
                    return datetime.strptime(string_value, iso_format)
                except ValueError as e:
                    errors.append('%s' % e)
            assert errors
            raise ValidationError('Time data "%s" does not match any of the formats %s' % (string_value, ', '.join('"%s"' % x for x in iso_formats)))

        def datetime_render_value(value, **_):
            return value.strftime(iso_formats[0]) if value else ''

        setdefaults_path(
            kwargs,
            parse=datetime_parse,
            render_value=datetime_render_value,
        )
        return Field(**kwargs)
Пример #6
0
def member_from_model(model, factory_lookup, defaults_factory, factory_lookup_register_function=None, field_name=None, model_field=None, **kwargs):
    if model_field is None:
        # noinspection PyProtectedMember
        model_field = model._meta.get_field(field_name)

    setdefaults_path(
        kwargs,
        defaults_factory(model_field),
        name=field_name,
    )

    factory = factory_lookup.get(type(model_field), MISSING)

    if factory is MISSING:
        for django_field_type, func in reversed(factory_lookup.items()):
            if isinstance(model_field, django_field_type):
                factory = func
                break

    if factory is MISSING:  # pragma: no cover
        message = 'No factory for %s.' % type(model_field)
        if factory_lookup_register_function is not None:
            message += ' Register a factory with %s, you can also register one that returns None to not handle this field type' % factory_lookup_register_function.__name__
        raise AssertionError(message)

    return factory(model_field=model_field, model=model, **kwargs) if factory else None
Пример #7
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`.
        """

        setdefaults_path(
            kwargs,
            {'attrs__class__' + c: True
             for c in kwargs.get('css_class', {})})
        super(Column, self).__init__(**kwargs)
Пример #8
0
def foreign_key_factory(model_field, **kwargs):
    setdefaults_path(
        kwargs,
        choices=model_field.foreign_related_fields[0].model.objects.all(),
    )
    kwargs['model'] = model_field.foreign_related_fields[0].model
    return Field.choice_queryset(**kwargs)
Пример #9
0
 def many_to_many_factory(model_field, **kwargs):
     setdefaults_path(
         kwargs,
         choices=model_field.rel.to._default_manager.all(),
         model=model_field.foreign_related_fields[0].model,
     )
     return Column.multi_choice_queryset(model_field=model_field, **kwargs)
Пример #10
0
 def multi_choice_queryset(**kwargs):
     setdefaults_path(
         kwargs,
         attrs__multiple=True,
         choice_to_option=lambda form, field, choice: (choice, choice.pk, "%s" % choice, field.value_list and choice in field.value_list),
         is_list=True,
     )
     return Field.choice_queryset(**kwargs)
Пример #11
0
 def multi_choice_queryset(**kwargs):
     setdefaults_path(
         kwargs,
         attrs__multiple=True,
         choice_to_option=lambda form, field, choice: (choice, choice.pk, "%s" % choice, field.value_list and choice in field.value_list),
         is_list=True,
     )
     return Field.choice_queryset(**kwargs)
Пример #12
0
def test_setdefatults_path_retain_empty():
    actual = setdefaults_path(Namespace(a=Namespace()), a__b=Namespace())
    expected = Namespace(a__b=Namespace())
    assert expected == actual

    actual = setdefaults_path(Namespace(), attrs__class=Namespace())
    expected = Namespace(attrs__class=Namespace())
    assert expected == actual
Пример #13
0
def test_setdefatults_path_retain_empty():
    actual = setdefaults_path(Namespace(a=Namespace()), a__b=Namespace())
    expected = Namespace(a__b=Namespace())
    assert expected == actual

    actual = setdefaults_path(Namespace(), attrs__class=Namespace())
    expected = Namespace(attrs__class=Namespace())
    assert expected == actual
Пример #14
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)
Пример #15
0
    def phone_number(**kwargs):
        def phone_number_is_valid(parsed_data, **_):
            return re.match(r'^\+\d{1,3}(( |-)?\(\d+\))?(( |-)?\d+)+$', parsed_data, re.IGNORECASE), 'Please use format +<country code> (XX) XX XX. Example of US number: +1 (212) 123 4567 or +1 212 123 4567'

        setdefaults_path(
            kwargs,
            is_valid=phone_number_is_valid,
        )
        return Field(**kwargs)
Пример #16
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)
Пример #17
0
    def integer(**kwargs):
        def int_parse(string_value, **_):
            return int(string_value)

        setdefaults_path(
            kwargs,
            parse=int_parse,
        )
        return Field(**kwargs)
Пример #18
0
    def decimal(**kwargs):
        def decimal_parse(string_value, **_):
            return Decimal(string_value)

        setdefaults_path(
            kwargs,
            parse=decimal_parse,
        )
        return Field(**kwargs)
Пример #19
0
    def email(**kwargs):
        def email_parse(string_value, **_):
            return validate_email(string_value) or string_value

        setdefaults_path(
            kwargs,
            input_type='email',
            parse=email_parse,
        )
        return Field(**kwargs)
Пример #20
0
    def url(**kwargs):
        def url_parse(string_value, **_):
            return URLValidator(string_value) or string_value

        setdefaults_path(
            kwargs,
            input_type='email',
            parse=url_parse,
        )
        return Field(**kwargs)
Пример #21
0
 def info(value, **kwargs):
     """
     Shortcut to create an info entry.
     """
     setdefaults_path(
         kwargs,
         initial=value,
         editable=False,
         attr=None,
     )
     return Field(**kwargs)
Пример #22
0
    def multi_choice_queryset(**kwargs):
        def multi_choice_queryset_choice_to_option(field, choice, **_):
            return choice, choice.pk, "%s" % choice, field.value_list and choice in field.value_list

        setdefaults_path(
            kwargs,
            attrs__multiple=True,
            choice_to_option=multi_choice_queryset_choice_to_option,
            is_list=True,
        )
        return Field.choice_queryset(**kwargs)
Пример #23
0
 def info(value, **kwargs):
     """
     Shortcut to create an info entry.
     """
     setdefaults_path(
         kwargs,
         initial=value,
         editable=False,
         attr=None,
     )
     return Field(**kwargs)
Пример #24
0
    def file(**kwargs):
        def file_write_to_instance(field, instance, value):
            if value:
                default_write_to_instance(field=field, instance=instance, value=value)

        setdefaults_path(
            kwargs,
            input_type='file',
            template_string='{% extends "tri_form/table_form_row.html" %}{% block extra_content %}{{ field.value }}{% endblock %}',
            write_to_instance=file_write_to_instance,
        )
        return Field(**kwargs)
Пример #25
0
    def file(**kwargs):
        def file_write_to_instance(field, instance, value):
            if value:
                default_write_to_instance(field=field, instance=instance, value=value)

        setdefaults_path(
            kwargs,
            input_type='file',
            template_string='{% extends "tri_form/table_form_row.html" %}{% block extra_content %}{{ field.value }}{% endblock %}',
            write_to_instance=file_write_to_instance,
        )
        return Field(**kwargs)
Пример #26
0
    def float(**kwargs):
        def parse_float(string_value, **_):
            try:
                return float(string_value)
            except ValueError:
                # Acrobatics so we get equal formatting in python 2/3
                raise ValueError("could not convert string to float: %s" % string_value)

        setdefaults_path(
            kwargs,
            parse=parse_float,
        )
        return Field(**kwargs)
Пример #27
0
    def float(**kwargs):
        def parse_float(string_value, **_):
            try:
                return float(string_value)
            except ValueError:
                # Acrobatics so we get equal formatting in python 2/3
                raise ValueError("could not convert string to float: %s" % string_value)

        setdefaults_path(
            kwargs,
            parse=parse_float,
        )
        return Field(**kwargs)
Пример #28
0
 def boolean(**kwargs):
     """
     Boolean field. Tries hard to parse a boolean value from its input.
     """
     setdefaults_path(
         kwargs,
         parse=lambda string_value, **_: bool_parse(string_value),
         required=False,
         template='tri_form/{style}_form_row_checkbox.html',
         input_template='tri_form/checkbox.html',
         is_boolean=True,
     )
     return Field(**kwargs)
Пример #29
0
 def boolean(**kwargs):
     """
     Boolean field. Tries hard to parse a boolean value from its input.
     """
     setdefaults_path(
         kwargs,
         parse=lambda string_value, **_: bool_parse(string_value),
         required=False,
         template='tri_form/{style}_form_row_checkbox.html',
         input_template='tri_form/checkbox.html',
         is_boolean=True,
     )
     return Field(**kwargs)
Пример #30
0
 def heading(label, show=True, template='tri_form/heading.html', **kwargs):
     """
     Shortcut to create a fake input that performs no parsing but is useful to separate sections of a form.
     """
     setdefaults_path(
         kwargs,
         label=label,
         show=show,
         template=template,
         editable=False,
         attr=None,
         name='@@heading@@',
     )
     return Field(**kwargs)
Пример #31
0
 def heading(label, show=True, template='tri_form/heading.html', **kwargs):
     """
     Shortcut to create a fake input that performs no parsing but is useful to separate sections of a form.
     """
     setdefaults_path(
         kwargs,
         label=label,
         show=show,
         template=template,
         editable=False,
         attr=None,
         name='@@heading@@',
     )
     return Field(**kwargs)
Пример #32
0
    def choice(**kwargs):
        """
        Shortcut for single choice field. If required is false it will automatically add an option first with the value '' and the title '---'. To override that text pass in the parameter empty_label.
        :param empty_label: default '---'
        :param choices: list of objects
        :param choice_to_option: callable with three arguments: form, field, choice. Convert from a choice object to a tuple of (choice, value, label, selected), the last three for the <option> element
        """
        assert 'choices' in kwargs

        setdefaults_path(
            kwargs,
            required=True,
            is_list=False,
            empty_label='---',
        )

        if not kwargs['required'] and not kwargs['is_list']:
            original_parse = kwargs.get('parse', default_parse)

            def parse(form, field, string_value):
                return original_parse(form=form, field=field, string_value=string_value)

            kwargs.update(
                parse=parse
            )

        def choice_is_valid(form, field, parsed_data):
            del form
            return parsed_data in field.choices, '%s not in available choices' % parsed_data

        def choice_post_validation(form, field):
            choice_tuples = (field.choice_to_option(form=form, field=field, choice=choice) for choice in field.choices)
            if not field.required and not field.is_list:
                choice_tuples = chain([field.empty_choice_tuple], choice_tuples)
            field.choice_tuples = choice_tuples

        def choice_choice_to_option(form, field, choice):
            return choice, "%s" % choice, "%s" % choice, choice == field.value

        setdefaults_path(
            kwargs,
            empty_choice_tuple=(None, '', kwargs['empty_label'], True),
            choice_to_option=choice_choice_to_option,
            input_template='tri_form/choice.html',
            is_valid=choice_is_valid,
            post_validation=choice_post_validation,
        )

        return Field(**kwargs)
Пример #33
0
    def time(**kwargs):
        iso_format = '%H:%M:%S'

        def time_parse(string_value, **_):
            try:
                return datetime.strptime(string_value, iso_format).time()
            except ValueError as e:
                raise ValidationError(str(e))

        setdefaults_path(
            kwargs,
            parse=time_parse,
            render_value=lambda value, **_: value.strftime(iso_format),
        )
        return Field(**kwargs)
Пример #34
0
    def date(**kwargs):
        iso_format = '%Y-%m-%d'

        def date_parse(string_value, **_):
            try:
                return datetime.strptime(string_value, iso_format).date()
            except ValueError as e:
                raise ValidationError(str(e))

        setdefaults_path(
            kwargs,
            parse=date_parse,
            render_value=lambda value, **_: value.strftime(iso_format) if value else '',
        )
        return Field(**kwargs)
Пример #35
0
    def date(**kwargs):
        iso_format = '%Y-%m-%d'

        def date_parse(string_value, **_):
            try:
                return datetime.strptime(string_value, iso_format).date()
            except ValueError as e:
                raise ValidationError(str(e))

        setdefaults_path(
            kwargs,
            parse=date_parse,
            render_value=lambda value, **_: value.strftime(iso_format) if value else '',
        )
        return Field(**kwargs)
Пример #36
0
    def time(**kwargs):
        iso_format = '%H:%M:%S'

        def time_parse(string_value, **_):
            try:
                return datetime.strptime(string_value, iso_format).time()
            except ValueError as e:
                raise ValidationError(str(e))

        setdefaults_path(
            kwargs,
            parse=time_parse,
            render_value=lambda value, **_: value.strftime(iso_format),
        )
        return Field(**kwargs)
Пример #37
0
def test_setdefaults_callable_backward_not_namespace():
    actual = setdefaults_path(
        Namespace(foo__x=17),
        foo=EMPTY,
    )
    expected = Namespace(foo__x=17)
    assert expected == actual
Пример #38
0
def test_setdefaults_path_ordering():
    expected = Struct(x=Struct(y=17, z=42))

    actual_foo = setdefaults_path(Struct(),
                                  OrderedDict([
                                      ('x', {'z': 42}),
                                      ('x__y', 17),
                                  ]))
    assert actual_foo == expected

    actual_bar = setdefaults_path(Struct(),
                                  OrderedDict([
                                      ('x__y', 17),
                                      ('x', {'z': 42}),
                                  ]))
    assert actual_bar == expected
Пример #39
0
 def bind_columns():
     for index, column in enumerate(self.columns):
         values = evaluate_recursive(Struct(column), table=self, column=column)
         values = setdefaults_path(
             Struct(), self.column.get(column.name, {}), values, column=column, table=self, index=index
         )
         yield BoundColumn(**values)
Пример #40
0
    def choice_queryset(**kwargs):

        def choice_queryset_is_valid(form, field, parsed_data):
            del form
            return field.choices.filter(pk=parsed_data.pk).exists(), '%s not in available choices' % (field.raw_data or ', '.join(field.raw_data_list))

        def choice_queryset_endpoint_dispatch(field, value, **_):
            limit = 10
            result = field.choices.filter(**{field.extra.endpoint_attr + '__icontains': value}).values_list(*['pk', field.extra.endpoint_attr])
            return [
                dict(
                    id=row[0],
                    text=row[1],
                )
                for row in result[:limit]
            ]

        kwargs = setdefaults_path(
            Struct(),
            kwargs,
            parse=lambda form, field, string_value: field.model.objects.get(pk=string_value) if string_value else None,
            choice_to_option=lambda form, field, choice: (choice, choice.pk, "%s" % choice, choice == field.value),
            endpoint_path=lambda form, field: '__' + form.endpoint_dispatch_prefix + '__field__' + field.name,
            endpoint_dispatch=choice_queryset_endpoint_dispatch,
            extra__endpoint_attr='name',
            is_valid=choice_queryset_is_valid,
        )
        return Field.choice(**kwargs)
Пример #41
0
    def choice_queryset(**kwargs):

        def choice_queryset_is_valid(form, field, parsed_data):
            del form
            return field.choices.filter(pk=parsed_data.pk).exists(), '%s not in available choices' % (field.raw_data or ', '.join(field.raw_data_list))

        def choice_queryset_endpoint_dispatch(field, value, **_):
            limit = 10
            result = field.choices.filter(**{field.extra.endpoint_attr + '__icontains': value}).values_list(*['pk', field.extra.endpoint_attr])
            return [
                dict(
                    id=row[0],
                    text=row[1],
                )
                for row in result[:limit]
            ]

        kwargs = setdefaults_path(
            Struct(),
            kwargs,
            parse=lambda form, field, string_value: field.model.objects.get(pk=string_value) if string_value else None,
            choice_to_option=lambda form, field, choice: (choice, choice.pk, "%s" % choice, choice == field.value),
            endpoint_path=lambda form, field: '__' + form.endpoint_dispatch_prefix + '__field__' + field.name,
            endpoint_dispatch=choice_queryset_endpoint_dispatch,
            extra__endpoint_attr='name',
            is_valid=choice_queryset_is_valid,
        )
        return Field.choice(**kwargs)
Пример #42
0
 def __init__(self, **kwargs):
     new_kwargs = setdefaults_path(
         Struct(),
         kwargs,
         bulk__attr=kwargs.get('attr'),
         query__attr=kwargs.get('attr'),
     )
     super(BoundColumn, self).__init__(**new_kwargs)
Пример #43
0
    def choice(**kwargs):
        """
        Shortcut for single choice field. If required is false it will automatically add an option first with the value '' and the title '---'. To override that text pass in the parameter empty_label.
        :param empty_label: default '---'
        :param choices: list of objects
        :param choice_to_option: callable with three arguments: form, field, choice. Convert from a choice object to a tuple of (choice, value, label, selected), the last three for the <option> element
        """
        assert 'choices' in kwargs

        setdefaults_path(
            kwargs,
            required=True,
            is_list=False,
            empty_label='---',
        )

        if not kwargs['required'] and not kwargs['is_list']:
            original_parse = kwargs.get('parse', default_parse)

            def parse(form, field, string_value):
                return original_parse(form=form, field=field, string_value=string_value)

            kwargs.update(
                parse=parse
            )

        def choice_is_valid(form, field, parsed_data):
            del form
            return parsed_data in field.choices, '%s not in available choices' % parsed_data

        def post_validation(form, field):
            choice_tuples = (field.choice_to_option(form=form, field=field, choice=choice) for choice in field.choices)
            if not field.required and not field.is_list:
                choice_tuples = chain([field.empty_choice_tuple], choice_tuples)
            field.choice_tuples = choice_tuples

        setdefaults_path(
            kwargs,
            empty_choice_tuple=(None, '', kwargs['empty_label'], True),
            choice_to_option=lambda form, field, choice: (choice, "%s" % choice, "%s" % choice, choice == field.value),
            input_template='tri_form/choice.html',
            is_valid=choice_is_valid,
            post_validation=post_validation,
        )

        return Field(**kwargs)
Пример #44
0
def test_no_call_target_overwrite():
    def f():
        pass

    def b():
        pass

    x = setdefaults_path(
        dict(foo={}),
        foo=f,
    )
    assert dict(foo=Namespace(call_target=f)) == x

    y = setdefaults_path(
        x,
        foo=b,
    )
    assert dict(foo=Namespace(call_target=f)) == y
Пример #45
0
 def boolean_tri_state(**kwargs):
     kwargs = setdefaults_path(
         Struct(),
         kwargs,
         query__show=True,
         query__gui__show=True,
         query__gui=Field.choice,
         query__gui__choices=[True, False],
         query__gui__parse=lambda string_value, **_: bool_parse(string_value),
     )
     return Column.from_model(**kwargs)
Пример #46
0
def test_setdefaults_path_ordering():
    expected = Struct(x=Struct(y=17, z=42))

    actual_foo = setdefaults_path(
        Struct(), OrderedDict([
            ('x', {
                'z': 42
            }),
            ('x__y', 17),
        ]))
    assert actual_foo == expected

    actual_bar = setdefaults_path(
        Struct(), OrderedDict([
            ('x__y', 17),
            ('x', {
                'z': 42
            }),
        ]))
    assert actual_bar == expected
Пример #47
0
def list_model(request, app_name, model_name, app, **kwargs):
    kwargs = setdefaults_path(
        kwargs,
        table__data=apps.all_models[app_name][model_name].objects.all(),
        table__extra_fields=[Column.edit(after=0, cell__url=lambda row, **_: '%s/edit/' % row.pk)],
    )
    return render_table_to_response(
        request,
        template='base.html',
        links=[Link(title='Create %s' % model_name.replace('_', ' '), url='create/')],
        **kwargs
    )
Пример #48
0
def member_from_model(model, factory_lookup, defaults_factory, field_name=None, model_field=None, **kwargs):
    if model_field is None:
        # noinspection PyProtectedMember
        model_field = model._meta.get_field(field_name)

    setdefaults_path(
        kwargs,
        defaults_factory(model_field),
        name=field_name,
    )

    factory = factory_lookup.get(type(model_field), MISSING)

    if factory is MISSING:
        for django_field_type, func in reversed(factory_lookup.items()):
            if isinstance(model_field, django_field_type):
                factory = func
                break

    if factory is MISSING:  # pragma: no cover
        raise AssertionError('No factory for %s. Register a factory with tri.form.register_field_factory, you can also register one that returns None to not handle this field type' % type(model_field))

    return factory(model_field=model_field, model=model, **kwargs) if factory else None
Пример #49
0
 def generate_variables():
     for column in self.bound_columns:
         if column.query.show:
             query_kwargs = setdefaults_path(
                 Struct(), column.query,
                 dict(
                     name=column.name,
                     gui__label=column.display_name,
                     attr=column.attr,
                     model=column.table.Meta.model,
                 ), {
                     'class': Variable,
                 })
             yield query_kwargs.pop('class')(**query_kwargs)
Пример #50
0
 def generate_variables():
     for column in self.bound_columns:
         if column.query.show:
             query_kwargs = setdefaults_path(
                 Struct(),
                 column.query,
                 dict(
                     name=column.name,
                     gui__label=column.display_name,
                     attr=column.attr,
                     model=column.table.model,
                 ),
                 {"class": Variable},
             )
             yield query_kwargs.pop("class")(**query_kwargs)
Пример #51
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`.
        """

        setdefaults_path(kwargs, {"attrs__class__" + c: True for c in kwargs.get("css_class", {})})
        super(Column, self).__init__(**kwargs)
Пример #52
0
def list_model(request, app_name, model_name, app, **kwargs):
    kwargs = setdefaults_path(
        kwargs,
        table__data=apps.all_models[app_name][model_name].objects.all(),
        table__extra_fields=[
            Column.edit(after=0,
                        cell__url=lambda row, **_: '%s/edit/' % row.pk)
        ],
    )
    return render_table_to_response(request,
                                    template='base.html',
                                    links=[
                                        Link(title='Create %s' %
                                             model_name.replace('_', ' '),
                                             url='create/')
                                    ],
                                    **kwargs)
Пример #53
0
 def generate_bulk_fields():
     for column in self.bound_columns:
         if column.bulk.show:
             bulk_kwargs = setdefaults_path(
                 Struct(), column.bulk,
                 dict(
                     name=column.name,
                     attr=column.attr,
                     required=False,
                     empty_choice_tuple=(None, '', '---', True),
                     model=self.Meta.model,
                 ), {
                     'class': Field.from_model,
                 })
             if bulk_kwargs['class'] == Field.from_model:
                 bulk_kwargs['field_name'] = column.attr
             yield bulk_kwargs.pop('class')(**bulk_kwargs)
Пример #54
0
 def radio(**kwargs):
     setdefaults_path(
         kwargs,
         input_template='tri_form/radio.html',
     )
     return Field.choice(**kwargs)
Пример #55
0
 def decimal(**kwargs):
     setdefaults_path(
         kwargs,
         parse=lambda string_value, **_: Decimal(string_value),
     )
     return Field(**kwargs)
Пример #56
0
 def password(**kwargs):
     setdefaults_path(
         kwargs,
         input_type='password',
     )
     return Field(**kwargs)
Пример #57
0
 def phone_number(**kwargs):
     setdefaults_path(
         kwargs,
         is_valid=lambda form, field, parsed_data: (re.match(r'^\+\d{1,3}(( |-)?\(\d+\))?(( |-)?\d+)+$', parsed_data, re.IGNORECASE), 'Please use format +<country code> (XX) XX XX. Example of US number: +1 (212) 123 4567 or +1 212 123 4567'),
     )
     return Field(**kwargs)
Пример #58
0
 def integer(**kwargs):
     setdefaults_path(
         kwargs,
         parse=lambda string_value, **_: int(string_value),
     )
     return Field(**kwargs)
Пример #59
0
 def textarea(**kwargs):
     setdefaults_path(
         kwargs,
         input_template='tri_form/text.html',
     )
     return Field(**kwargs)
Пример #60
0
 def text(**kwargs):
     setdefaults_path(
         kwargs,
         input_type='text',
     )
     return Field(**kwargs)