Exemple #1
0
    def _prepare_evaluate_members(self):
        self.shown_bound_columns = [
            bound_column for bound_column in self.bound_columns
            if bound_column.show
        ]

        self.Meta = evaluate_recursive(self.Meta, table=self)

        if 'class' in self.Meta.attrs and isinstance(self.Meta.attrs['class'],
                                                     string_types):
            self.Meta.attrs['class'] = {
                k: True
                for k in self.Meta.attrs['class'].split(' ')
            }
        else:
            self.Meta.attrs['class'] = {}
        self.Meta.attrs.update(extract_subkeys(self.Meta, 'attrs'))
        self.Meta.attrs = collect_namespaces(self.Meta.attrs)

        if 'class' in self.Meta.row__attrs and isinstance(
                self.Meta.row__attrs['class'], string_types):
            self.Meta.row__attrs['class'] = {
                k: True
                for k in self.Meta.row__attrs['class'].split(' ')
            }
        else:
            self.Meta.row__attrs['class'] = {}
        self.Meta.row__attrs.update(extract_subkeys(self.Meta, 'row__attrs'))
        self.Meta.row__attrs = collect_namespaces(self.Meta.row__attrs)

        if not self.Meta.sortable:
            for bound_column in self.bound_columns:
                bound_column.sortable = False
Exemple #2
0
def create_or_edit_object(request,
                          model,
                          is_create,
                          instance=None,
                          redirect_to=None,
                          on_save=lambda **kwargs: None,
                          render=render_to_response,
                          redirect=lambda request, redirect_to, form:
                          HttpResponseRedirect(redirect_to),
                          **kwargs):
    kwargs.setdefault('form__class', Form.from_model)
    kwargs.setdefault('template_name',
                      'tri_form/create_or_edit_object_block.html')
    p = extract_subkeys(
        kwargs,
        'form',
        defaults=dict(request=request,
                      model=model,
                      instance=instance,
                      data=request.POST if request.method == 'POST' else None))
    form = p.pop('class')(**p)

    # noinspection PyProtectedMember
    model_verbose_name = kwargs.get('model_verbose_name',
                                    model._meta.verbose_name.replace('_', ' '))

    if request.method == 'POST' and form.is_valid():
        if is_create:
            assert instance is None
            instance = model()
            for field in form.fields:
                if not field.extra.get('django_related_field', False):
                    form.apply_field(field=field, instance=instance)

            instance.save()
        form.apply(instance)
        instance.save()

        kwargs['instance'] = instance
        on_save(**kwargs)

        return create_or_edit_object_redirect(is_create, redirect_to, request,
                                              redirect, form)

    c = {
        'form': form,
        'is_create': is_create,
        'object_name': model_verbose_name,
    }
    c.update(kwargs.get('render__context', {}))
    kwargs.pop('render__context', None)

    kwargs_for_render = extract_subkeys(
        kwargs, 'render', {
            'context_instance': RequestContext(request, c),
            'template_name': kwargs['template_name'],
        })
    return render(**kwargs_for_render)
Exemple #3
0
def create_or_edit_object(
        request,
        model,
        is_create,
        instance=None,
        redirect_to=None,
        on_save=lambda **kwargs: None,
        render=render_to_response,
        redirect=lambda request, redirect_to, form: HttpResponseRedirect(redirect_to),
        **kwargs):
    kwargs.setdefault('form__class', Form.from_model)
    kwargs.setdefault('template_name', 'tri_form/create_or_edit_object_block.html')
    p = extract_subkeys(kwargs, 'form', defaults=dict(request=request,
                                                      model=model,
                                                      instance=instance,
                                                      data=request.POST if request.method == 'POST' else None))
    form = p.pop('class')(**p)

    # noinspection PyProtectedMember
    model_verbose_name = kwargs.get('model_verbose_name', model._meta.verbose_name.replace('_', ' '))

    if request.method == 'POST' and form.is_valid():
        if is_create:
            assert instance is None
            instance = model()
            for field in form.fields:
                if not field.extra.get('django_related_field', False):
                    form.apply_field(field=field, instance=instance)

            instance.save()
        form.apply(instance)
        instance.save()

        kwargs['instance'] = instance
        on_save(**kwargs)

        return create_or_edit_object_redirect(is_create, redirect_to, request, redirect, form)

    c = {
        'form': form,
        'is_create': is_create,
        'object_name': model_verbose_name,
    }
    c.update(kwargs.get('render__context', {}))
    kwargs.pop('render__context', None)

    kwargs_for_render = extract_subkeys(kwargs, 'render', {
        'context_instance': RequestContext(request, c),
        'template_name': kwargs['template_name'],
    })
    return render(**kwargs_for_render)
def test_extract_subkeys():
    foo = {
        'foo__foo': 1,
        'foo__bar': 2,
        'baz': 3,
    }
    assert extract_subkeys(foo, 'foo', defaults={'quux': 4}) == {
        'foo': 1,
        'bar': 2,
        'quux': 4,
    }

    assert extract_subkeys(foo, 'foo') == {
        'foo': 1,
        'bar': 2,
    }
Exemple #5
0
    def __init__(self, request=None, variables=None, variables_dict=None, endpoint_dispatch_prefix='query', **kwargs):  # variables=None to make pycharm tooling not confused
        """
        :type variables: list of Variable
        :type request: django.http.request.HttpRequest
        """
        self.endpoint_dispatch_prefix = endpoint_dispatch_prefix
        self.request = request
        self._form = None

        def generate_variables():
            if variables is not None:
                for variable in variables:
                    yield variable
            for name, variable in variables_dict.items():
                dict.__setitem__(variable, 'name', name)
                yield variable
        self.variables = sort_after(list(generate_variables()))

        def generate_bound_variables():
            for x in self.variables:
                yield BoundVariable(**merged(
                    Struct(x),
                    query=self,
                    attr=x.attr if x.attr is not MISSING else x.name
                ))
        bound_variables = list(generate_bound_variables())

        bound_variables = [evaluate_recursive(x, query=self, variable=x) for x in bound_variables]
        self.bound_variables = filter_show_recursive(bound_variables)

        self.bound_variable_by_name = {variable.name: variable for variable in self.bound_variables}

        self.gui_kwargs = extract_subkeys(kwargs, 'gui')
Exemple #6
0
def test_extract_subkeys():
    foo = {
        'foo__foo': 1,
        'foo__bar': 2,
        'baz': 3,
    }
    assert extract_subkeys(foo, 'foo', defaults={'quux': 4}) == {
        'foo': 1,
        'bar': 2,
        'quux': 4,
    }

    assert extract_subkeys(foo, 'foo') == {
        'foo': 1,
        'bar': 2,
    }
Exemple #7
0
    def __init__(self, table, row, row_index):
        self.table = table
        """ :type : Table """
        self.row = row
        """ :type : object """
        self.row_index = row_index

        args = Struct(
            evaluate_recursive(extract_subkeys(table.Meta, 'row'),
                               table=table,
                               row=row))
        self.template = args.template
        self.attrs = args.attrs
Exemple #8
0
    def fields_from_model(model, include=None, exclude=None, **kwargs):
        def should_include(name):
            if exclude is not None and name in exclude:
                return False
            if include is not None:
                return name in include
            return True

        fields = []
        # noinspection PyProtectedMember
        for field, _ in model._meta.get_fields_with_model():
            if should_include(field.name) and not isinstance(field, AutoField):
                subkeys = extract_subkeys(kwargs, field.name)
                foo = subkeys.get('class', Field.from_model)(name=field.name, model=model, model_field=field, **subkeys)
                if isinstance(foo, list):
                    fields.extend(foo)
                else:
                    fields.append(foo)
        return fields
Exemple #9
0
    def __init__(self, request=None, variables=None, **kwargs):  # variables=None to make pycharm tooling not confused
        """
        :type variables: list of Variable
        :type request: django.http.request.HttpRequest
        """
        self.request = request

        assert variables is not None
        if isinstance(variables, dict):  # Declarative case
            self.variables = [merged(variable, name=name) for name, variable in variables.items()]
        else:
            self.variables = variables

        bound_variables = [BoundVariable(**merged(Struct(x), query=self)) for x in self.variables]
        bound_variables = [evaluate_recursive(x, query=self, variable=x) for x in bound_variables]
        self.bound_variables = filter_show_recursive(bound_variables)

        self.bound_variable_by_name = {variable.name: variable for variable in self.bound_variables}

        self.gui_kwargs = extract_subkeys(kwargs, 'gui')
Exemple #10
0
def create_or_edit_object(
        request,
        model,
        is_create,
        instance=None,
        redirect_to=None,
        on_save=lambda **kwargs: None,
        render=render_to_response,
        redirect=lambda request, redirect_to, form: HttpResponseRedirect(redirect_to),
        **kwargs):
    kwargs = setdefaults_path(
        Struct(),
        kwargs,
        template_name='tri_form/create_or_edit_object_block.html',
        form__class=Form.from_model,
        form__request=request,
        form__model=model,
        form__instance=instance,
        form__data=request.POST if request.method == 'POST' else None,
    )
    p = kwargs.form
    form = p.pop('class')(**p)

    for key, value in request.GET.items():
        if key.startswith('__'):
            remaining_key = key[2:]
            expected_prefix = form.endpoint_dispatch_prefix
            if expected_prefix is not None:
                parts = remaining_key.split('__', 1)
                prefix = parts.pop(0)
                if prefix != expected_prefix:
                    return
                remaining_key = parts[0] if parts else None
            data = form.endpoint_dispatch(key=remaining_key, value=value)
            if data:
                return HttpResponse(json.dumps(data), content_type='application/json')

    # noinspection PyProtectedMember
    model_verbose_name = kwargs.get('model_verbose_name', model._meta.verbose_name.replace('_', ' '))

    if request.method == 'POST' and form.is_valid():
        if is_create:
            assert instance is None
            instance = model()
            for field in form.fields:
                if not field.extra.get('django_related_field', False):
                    form.apply_field(field=field, instance=instance)

            instance.save()
        form.apply(instance)
        instance.save()

        kwargs['instance'] = instance
        on_save(**kwargs)

        return create_or_edit_object_redirect(is_create, redirect_to, request, redirect, form)

    c = {
        'form': form,
        'is_create': is_create,
        'object_name': model_verbose_name,
    }
    c.update(kwargs.get('render_context', {}))
    kwargs.pop('render_context', None)

    kwargs_for_render = extract_subkeys(kwargs, 'render', {
        'context_instance': RequestContext(request, c),
        'template_name': kwargs['template_name'],
    })
    return render(**kwargs_for_render)
Exemple #11
0
    def __init__(self,
                 data=None,
                 request=None,
                 columns=None,
                 columns_dict=None,
                 **kwargs):
        """
        :param data: a list of QuerySet of objects
        :param columns: (use this only when not using the declarative style) a list of Column objects
        :param attrs: dict of strings to string/callable of HTML attributes to apply to the table
        :param row__attrs: dict of strings to string/callable of HTML attributes to apply to the row. Callables are passed the row as argument.
        :param row__template: name of template to use for rendering the row
        :param bulk_filter: filters to apply to the QuerySet before performing the bulk operation
        :param bulk_exclude: exclude filters to apply to the QuerySet before performing the bulk operation
        :param sortable: set this to false to turn off sorting for all columns
        :param filter__template:
        :param header__template:
        :param links__template:

        """

        self._has_prepared = False

        if data is None:
            assert 'model' in kwargs and kwargs['model'] is not None
            data = kwargs['model'].objects.all()

        self.data = data
        self.request = request

        if isinstance(self.data, QuerySet):
            kwargs['model'] = data.model

        def generate_columns():
            for column in columns if columns is not None else []:
                yield column
            for name, column in columns_dict.items():
                dict.__setitem__(column, 'name', name)
                yield column

        self.columns = sort_after(list(generate_columns()))
        """:type : list of Column"""

        assert len(
            self.columns
        ) > 0, 'columns must be specified. It is only set to None to make linting tools not give false positives on the declarative style'

        self.bound_columns = None
        self.shown_bound_columns = None
        self.bound_column_by_name = None

        self.Meta = self.get_meta()
        self.Meta.update(**kwargs)

        self.header_levels = None
        self.query = None
        self.query_form = None
        self.query_error = None
        self.bulk_form = None

        self.query_kwargs = extract_subkeys(kwargs, 'query')
        self.bulk_kwargs = extract_subkeys(kwargs, 'bulk')
        self.endpoint = extract_subkeys(kwargs, 'endpoint')