Exemple #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)
Exemple #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)
Exemple #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)
Exemple #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)
Exemple #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)
Exemple #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
Exemple #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)
Exemple #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)
Exemple #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)
Exemple #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)
Exemple #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)
Exemple #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
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
Exemple #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)
Exemple #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)
Exemple #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)
Exemple #17
0
    def integer(**kwargs):
        def int_parse(string_value, **_):
            return int(string_value)

        setdefaults_path(
            kwargs,
            parse=int_parse,
        )
        return Field(**kwargs)
Exemple #18
0
    def decimal(**kwargs):
        def decimal_parse(string_value, **_):
            return Decimal(string_value)

        setdefaults_path(
            kwargs,
            parse=decimal_parse,
        )
        return Field(**kwargs)
Exemple #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)
Exemple #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)
Exemple #21
0
 def info(value, **kwargs):
     """
     Shortcut to create an info entry.
     """
     setdefaults_path(
         kwargs,
         initial=value,
         editable=False,
         attr=None,
     )
     return Field(**kwargs)
Exemple #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)
Exemple #23
0
 def info(value, **kwargs):
     """
     Shortcut to create an info entry.
     """
     setdefaults_path(
         kwargs,
         initial=value,
         editable=False,
         attr=None,
     )
     return Field(**kwargs)
Exemple #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)
Exemple #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)
Exemple #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)
Exemple #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)
Exemple #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)
Exemple #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)
Exemple #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)
Exemple #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)
Exemple #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)
Exemple #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)
Exemple #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)
Exemple #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)
Exemple #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)
Exemple #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
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
Exemple #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)
Exemple #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)
Exemple #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)
Exemple #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)
Exemple #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)
Exemple #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
Exemple #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)
Exemple #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
Exemple #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
    )
Exemple #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
Exemple #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)
Exemple #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)
Exemple #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)
Exemple #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)
Exemple #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)
Exemple #54
0
 def radio(**kwargs):
     setdefaults_path(
         kwargs,
         input_template='tri_form/radio.html',
     )
     return Field.choice(**kwargs)
Exemple #55
0
 def decimal(**kwargs):
     setdefaults_path(
         kwargs,
         parse=lambda string_value, **_: Decimal(string_value),
     )
     return Field(**kwargs)
Exemple #56
0
 def password(**kwargs):
     setdefaults_path(
         kwargs,
         input_type='password',
     )
     return Field(**kwargs)
Exemple #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)
Exemple #58
0
 def integer(**kwargs):
     setdefaults_path(
         kwargs,
         parse=lambda string_value, **_: int(string_value),
     )
     return Field(**kwargs)
Exemple #59
0
 def textarea(**kwargs):
     setdefaults_path(
         kwargs,
         input_template='tri_form/text.html',
     )
     return Field(**kwargs)
Exemple #60
0
 def text(**kwargs):
     setdefaults_path(
         kwargs,
         input_type='text',
     )
     return Field(**kwargs)