Example #1
0
    def get_kwargs(self, field, kwargs):
        """Setting data-display-text and data-value manually.
        """
        assert field.name == 'status', \
                "A field other than 'status' is using the StatusEnumEnabledXEditableWidget"

        kwargs['data-type'] = 'select'

        choices = []
        for value, label, selected in field.iter_choices():
            try:
                label = text_type(label)
            except TypeError:
                # unable to display text value
                label = ''

            status_enum = getattr(AccountStatus, text_type(label))
            l = AccountStatusHelper.translate(status_enum)
            choices.append({'value': text_type(value), 'text': l})

            if selected:
                kwargs['data-display-text'] = l
                kwargs['data-value'] = text_type(value)

        self.set_choices(kwargs, choices)

        return kwargs
Example #2
0
def get_field_id(field):
    """
    get and format id from field
    :rtype: text_type
    """
    field_id = field.get_pk()
    if isinstance(field_id, tuple):
        return tuple(text_type(_) for _ in field_id)

    return text_type(field_id)
Example #3
0
def get_obj_pk(obj, pk):
    """
    get and format pk from obj
    :rtype: text_type
    """

    if isinstance(pk, tuple):
        return tuple(text_type(getattr(obj, k)) for k in pk)

    return text_type(getattr(obj, pk))
Example #4
0
def get_field_id(field):
    """
    get and format id from field
    :rtype: text_type
    """
    field_id = field.get_pk()
    if isinstance(field_id, tuple):
        return tuple(text_type(_) for _ in field_id)

    return text_type(field_id)
Example #5
0
def get_obj_pk(obj, pk):
    """
    get and format pk from obj
    :rtype: text_type
    """

    if isinstance(pk, tuple):
        return tuple(text_type(getattr(obj, k)) for k in pk)

    return text_type(getattr(obj, pk))
Example #6
0
    def get_sortable_columns(self):
        """
            Returns a dictionary of the sortable columns. Key is a model
            field name and value is sort column (for example - attribute).

            If `column_sortable_list` is set, will use it. Otherwise, will call
            `scaffold_sortable_columns` to get them from the model.
        """
        self._sortable_joins = dict()

        if self.column_sortable_list is None:
            return self.scaffold_sortable_columns()
        else:
            result = dict()

            for c in self.column_sortable_list:
                if isinstance(c, tuple):
                    if isinstance(c[1], tuple):
                        column, path = [], []
                        for item in c[1]:
                            column_item, path_item = tools.get_field_with_path(
                                self.model, item)
                            column.append(column_item)
                            path.append(path_item)
                        column_name = c[0]
                    else:
                        column, path = tools.get_field_with_path(
                            self.model, c[1])
                        column_name = c[0]
                else:
                    column, path = tools.get_field_with_path(self.model, c)
                    column_name = text_type(c)

                if path and (hasattr(path[0], 'property')
                             or isinstance(path[0], list)):
                    self._sortable_joins[column_name] = path
                elif path:
                    raise Exception("For sorting columns in a related table, "
                                    "column_sortable_list requires a string "
                                    "like '<relation name>.<column name>'. "
                                    "Failed on: {0}".format(c))
                else:
                    # column is in same table, use only model attribute name
                    if getattr(column, 'key', None) is not None:
                        column_name = column.key
                    else:
                        column_name = text_type(c)

                # column_name must match column_name used in `get_list_columns`
                result[column_name] = column

            return result
Example #7
0
    def get_list_columns(self):
        """
            Returns a list of tuples with the model field name and formatted
            field name. If `column_list` was set, returns it. Otherwise calls
            `scaffold_list_columns` to generate the list from the model.
        """
        if self.column_list is None:
            columns = self.scaffold_list_columns()

            # Filter excluded columns
            if self.column_exclude_list:
                columns = [
                    c for c in columns if c not in self.column_exclude_list
                ]

            return [(c, self.get_column_name(c)) for c in columns]
        else:
            columns = []

            for c in self.column_list:
                column, path = tools.get_field_with_path(self.model, c)

                if path:
                    # column is in another table, use full path
                    column_name = text_type(c)
                else:
                    # column is in same table, use only model attribute name
                    column_name = column.key

                visible_name = self.get_column_name(column_name)

                # column_name must match column_name in `get_sortable_columns`
                columns.append((column_name, visible_name))

            return columns
Example #8
0
    def get_list_columns(self):
        """
            Returns a list of tuples with the model field name and formatted
            field name. If `column_list` was set, returns it. Otherwise calls
            `scaffold_list_columns` to generate the list from the model.
        """
        if self.column_list is None:
            columns = self.scaffold_list_columns()

            # Filter excluded columns
            if self.column_exclude_list:
                columns = [c for c in columns
                           if c not in self.column_exclude_list]

            return [(c, self.get_column_name(c)) for c in columns]
        else:
            columns = []

            for c in self.column_list:
                column, path = tools.get_field_with_path(self.model, c)

                if path:
                    # column is in another table, use full path
                    column_name = text_type(c)
                else:
                    # column is in same table, use only model attribute name
                    column_name = column.key

                visible_name = self.get_column_name(column_name)

                # column_name must match column_name in `get_sortable_columns`
                columns.append((column_name, visible_name))

            return columns
Example #9
0
 def _get_object_list(self):
     if self._object_list is None:
         query = self.query or self.query_factory()
         get_pk = self.get_pk
         self._object_list = [(text_type(get_pk(obj)), obj)
                              for obj in query]
     return self._object_list
Example #10
0
    def handle_view_exception(self, exc):
        if isinstance(exc, IntegrityError):
            flash(
                gettext('Integrity error. %(message)s',
                        message=text_type(exc)), 'error')
            return True

        return super(ModelView, self).handle_view_exception(exc)
Example #11
0
def list_formatter(view, values):
    """
        Return string with comma separated values

        :param values:
            Value to check
    """
    return u', '.join(text_type(v) for v in values)
Example #12
0
def list_formatter(view, values):
    """
        Return string with comma separated values

        :param values:
            Value to check
    """
    return u', '.join(text_type(v) for v in values)
Example #13
0
    def handle_view_exception(self, exc):
        if isinstance(exc, IntegrityError):
            if current_app.config.get('ADMIN_RAISE_ON_VIEW_EXCEPTION'):
                raise
            else:
                flash(gettext('Integrity error. %(message)s', message=text_type(exc)), 'error')
            return True

        return super(ModelView, self).handle_view_exception(exc)
Example #14
0
    def get_actions_list(self):
        """
            Return a list and a dictionary of allowed actions.
        """
        actions = []
        actions_confirmation = {}

        for act in self._actions:
            name, text = act

            if self.is_action_allowed(name):
                actions.append((name, text_type(text)))

                confirmation = self._actions_data[name][2]
                if confirmation:
                    actions_confirmation[name] = text_type(confirmation)

        return actions, actions_confirmation
Example #15
0
    def handle_view_exception(self, exc):
        if isinstance(exc, IntegrityError):
            if current_app.config.get('ADMIN_RAISE_ON_VIEW_EXCEPTION'):
                raise
            else:
                flash(gettext('Integrity error. %(message)s', message=text_type(exc)), 'error')
            return True

        return super(ModelView, self).handle_view_exception(exc)
Example #16
0
    def handle_view_exception(self, exc):
        if isinstance(exc, IntegrityError):
            flash(
                gettext(
                    'Integrity error. %(message)s', message=text_type(exc)),
                'error')
            return True

        return super(ModelView, self).handle_view_exception(exc)
Example #17
0
    def get_actions_list(self):
        """
            Return a list and a dictionary of allowed actions.
        """
        actions = []
        actions_confirmation = {}

        for act in self._actions:
            name, text = act

            if self.is_action_allowed(name):
                actions.append((name, text_type(text)))

                confirmation = self._actions_data[name][2]
                if confirmation:
                    actions_confirmation[name] = text_type(confirmation)

        return actions, actions_confirmation
Example #18
0
    def get_column_names(self, only_columns, excluded_columns):
        """
            Returns a list of tuples with the model field name and formatted
            field name.

            Overridden to handle special columns like InstrumentedAttribute.

            :param only_columns:
                List of columns to include in the results. If not set,
                `scaffold_list_columns` will generate the list from the model.
            :param excluded_columns:
                List of columns to exclude from the results.
        """
        if excluded_columns:
            only_columns = [
                c for c in only_columns if c not in excluded_columns
            ]

        formatted_columns = []
        for c in only_columns:
            try:
                column, path = tools.get_field_with_path(self.model, c)

                if path:
                    # column is a relation (InstrumentedAttribute), use full path
                    column_name = text_type(c)
                else:
                    # column is in same table, use only model attribute name
                    if getattr(column, 'key', None) is not None:
                        column_name = column.key
                    else:
                        column_name = text_type(c)
            except AttributeError:
                # TODO: See ticket #1299 - allow virtual columns. Probably figure out
                # better way to handle it. For now just assume if column was not found - it
                # is virtual and there's column formatter for it.
                column_name = text_type(c)

            visible_name = self.get_column_name(column_name)

            # column_name must match column_name in `get_sortable_columns`
            formatted_columns.append((column_name, visible_name))

        return formatted_columns
Example #19
0
    def get_sortable_columns(self):
        """
            Returns a dictionary of the sortable columns. Key is a model
            field name and value is sort column (for example - attribute).

            If `column_sortable_list` is set, will use it. Otherwise, will call
            `scaffold_sortable_columns` to get them from the model.
        """
        self._sortable_joins = dict()

        if self.column_sortable_list is None:
            return self.scaffold_sortable_columns()
        else:
            result = dict()

            for c in self.column_sortable_list:
                if isinstance(c, tuple):
                    column, path = tools.get_field_with_path(self.model, c[1])
                    column_name = c[0]
                else:
                    column, path = tools.get_field_with_path(self.model, c)
                    column_name = text_type(c)

                if path and hasattr(path[0], "property"):
                    self._sortable_joins[column_name] = path
                elif path:
                    raise Exception(
                        "For sorting columns in a related table, "
                        "column_sortable_list requires a string "
                        "like '<relation name>.<column name>'. "
                        "Failed on: {0}".format(c)
                    )
                else:
                    # column is in same table, use only model attribute name
                    if getattr(column, "key", None) is not None:
                        column_name = column.key
                    else:
                        column_name = text_type(c)

                # column_name must match column_name used in `get_list_columns`
                result[column_name] = column

            return result
Example #20
0
    def get_column_names(self, only_columns, excluded_columns):
        """
            Returns a list of tuples with the model field name and formatted
            field name.

            Overridden to handle special columns like InstrumentedAttribute.

            :param only_columns:
                List of columns to include in the results. If not set,
                `scaffold_list_columns` will generate the list from the model.
            :param excluded_columns:
                List of columns to exclude from the results.
        """
        if excluded_columns:
            only_columns = [c for c in only_columns if c not in excluded_columns]

        formatted_columns = []
        for c in only_columns:
            try:
                column, path = tools.get_field_with_path(self.model, c)

                if path:
                    # column is a relation (InstrumentedAttribute), use full path
                    column_name = text_type(c)
                else:
                    # column is in same table, use only model attribute name
                    if getattr(column, 'key', None) is not None:
                        column_name = column.key
                    else:
                        column_name = text_type(c)
            except AttributeError:
                # TODO: See ticket #1299 - allow virtual columns. Probably figure out
                # better way to handle it. For now just assume if column was not found - it
                # is virtual and there's column formatter for it.
                column_name = text_type(c)

            visible_name = self.get_column_name(column_name)

            # column_name must match column_name in `get_sortable_columns`
            formatted_columns.append((column_name, visible_name))

        return formatted_columns
Example #21
0
    def get_column_names(self, only_columns, excluded_columns):
        """
            Returns a list of tuples with the model field name and formatted
            field name.

            Overridden to handle special columns like InstrumentedAttribute.

            :param only_columns:
                List of columns to include in the results. If not set,
                `scaffold_list_columns` will generate the list from the model.
            :param excluded_columns:
                List of columns to exclude from the results.
        """
        if excluded_columns:
            only_columns = [
                c for c in only_columns if c not in excluded_columns
            ]

        formatted_columns = []
        for c in only_columns:
            column, path = tools.get_field_with_path(self.model, c)

            if path:
                # column is a relation (InstrumentedAttribute), use full path
                column_name = text_type(c)
            else:
                # column is in same table, use only model attribute name
                if getattr(column, 'key', None) is not None:
                    column_name = column.key
                else:
                    column_name = text_type(c)

            visible_name = self.get_column_name(column_name)

            # column_name must match column_name in `get_sortable_columns`
            formatted_columns.append((column_name, visible_name))

        return formatted_columns
Example #22
0
    def get_column_names(self, only_columns, excluded_columns):
        """
            Returns a list of tuples with the model field name and formatted
            field name.

            Overridden to handle special columns like InstrumentedAttribute.

            :param only_columns:
                List of columns to include in the results. If not set,
                `scaffold_list_columns` will generate the list from the model.
            :param excluded_columns:
                List of columns to exclude from the results.
        """
        if excluded_columns:
            only_columns = [
                c for c in only_columns if c not in excluded_columns
            ]

        formatted_columns = []
        for c in only_columns:
            column, path = tools.get_field_with_path(self.model, c)

            if path:
                # column is a relation (InstrumentedAttribute), use full path
                column_name = text_type(c)
            else:
                # column is in same table, use only model attribute name
                if getattr(column, 'key', None) is not None:
                    column_name = column.key
                else:
                    column_name = text_type(c)

            visible_name = self.get_column_name(column_name)

            # column_name must match column_name in `get_sortable_columns`
            formatted_columns.append((column_name, visible_name))

        return formatted_columns
Example #23
0
    def convert_enum(self, column, field_args, **extra):
        available_choices = [(f, f) for f in column.type.enums]
        accepted_values = [key for key, val in available_choices]

        if column.nullable:
            field_args['allow_blank'] = column.nullable
            accepted_values.append(None)
            filters = field_args.get('filters', [])
            filters.append(lambda x: x or None)
            field_args['filters'] = filters

        field_args['choices'] = available_choices
        field_args['validators'].append(validators.AnyOf(accepted_values))
        field_args['coerce'] = lambda v: v.name if isinstance(v, Enum) else text_type(v)
        return form.Select2Field(**field_args)
Example #24
0
    def get_options(self, view):
        """
            Return list of predefined options.

            Override to customize behavior.

            :param view:
                Associated administrative view class.
        """
        options = self.options

        if options:
            if callable(options):
                options = options()

            return [(v, text_type(n)) for v, n in options]

        return None
Example #25
0
    def get_options(self, view):
        """
            Return list of predefined options.

            Override to customize behavior.

            :param view:
                Associated administrative view class.
        """
        options = self.options

        if options:
            if callable(options):
                options = options()

            return [(v, text_type(n)) for v, n in options]

        return None
Example #26
0
    def conv_String(self, column, field_args, **extra):
        if hasattr(column.type, 'enums'):
            accepted_values = list(column.type.enums)

            field_args['choices'] = [(f, f) for f in column.type.enums]

            if column.nullable:
                field_args['allow_blank'] = column.nullable
                accepted_values.append(None)

            field_args['validators'].append(validators.AnyOf(accepted_values))
            field_args['coerce'] = lambda v: v.name if isinstance(v, Enum) else text_type(v)

            return form.Select2Field(**field_args)

        if column.nullable:
            filters = field_args.get('filters', [])
            filters.append(lambda x: x or None)
            field_args['filters'] = filters

        self._string_common(column=column, field_args=field_args, **extra)
        return fields.StringField(**field_args)
Example #27
0
    def get_kwargs(self, subfield, kwargs):
        """
            Return extra kwargs based on the subfield type.
        """
        if subfield.type == 'StringField':
            kwargs['data-type'] = 'text'
        elif subfield.type == 'TextAreaField':
            kwargs['data-type'] = 'textarea'
            kwargs['data-rows'] = '5'
        elif subfield.type == 'BooleanField':
            kwargs['data-type'] = 'select'
            # data-source = dropdown options
            kwargs['data-source'] = json.dumps([{
                'value': '',
                'text': gettext('No')
            }, {
                'value': '1',
                'text': gettext('Yes')
            }])
            kwargs['data-role'] = 'x-editable-boolean'
        elif subfield.type == 'Select2Field':
            kwargs['data-type'] = 'select'
            choices = [{'value': x, 'text': y} for x, y in subfield.choices]

            # prepend a blank field to choices if allow_blank = True
            if getattr(subfield, 'allow_blank', False):
                choices.insert(0, {'value': '__None', 'text': ''})

            # json.dumps fixes issue with unicode strings not loading correctly
            kwargs['data-source'] = json.dumps(choices)
        elif subfield.type == 'DateField':
            kwargs['data-type'] = 'combodate'
            kwargs['data-format'] = 'YYYY-MM-DD'
            kwargs['data-template'] = 'YYYY-MM-DD'
        elif subfield.type == 'DateTimeField':
            kwargs['data-type'] = 'combodate'
            kwargs['data-format'] = 'YYYY-MM-DD HH:mm:ss'
            kwargs['data-template'] = 'YYYY-MM-DD  HH:mm:ss'
            # x-editable-combodate uses 1 minute increments
            kwargs['data-role'] = 'x-editable-combodate'
        elif subfield.type == 'TimeField':
            kwargs['data-type'] = 'combodate'
            kwargs['data-format'] = 'HH:mm:ss'
            kwargs['data-template'] = 'HH:mm:ss'
            kwargs['data-role'] = 'x-editable-combodate'
        elif subfield.type == 'IntegerField':
            kwargs['data-type'] = 'number'
        elif subfield.type in ['FloatField', 'DecimalField']:
            kwargs['data-type'] = 'number'
            kwargs['data-step'] = 'any'
        elif subfield.type in ['QuerySelectField', 'ModelSelectField']:
            # QuerySelectField and ModelSelectField are for relations
            kwargs['data-type'] = 'select'

            choices = []
            for choice in subfield:
                try:
                    choices.append({
                        'value': text_type(choice._value()),
                        'text': text_type(choice.label.text)
                    })
                except TypeError:
                    # unable to display text value
                    choices.append({
                        'value': text_type(choice._value()),
                        'text': ''
                    })

            # blank field is already included if allow_blank
            kwargs['data-source'] = json.dumps(choices)
        else:
            raise Exception('Unsupported field type: %s' % (type(subfield), ))

        return kwargs
Example #28
0
    def get_kwargs(self, field, kwargs):
        """
            Return extra kwargs based on the field type.
        """
        if field.type == 'StringField':
            kwargs['data-type'] = 'text'
        elif field.type == 'TextAreaField':
            kwargs['data-type'] = 'textarea'
            kwargs['data-rows'] = '5'
        elif field.type == 'BooleanField':
            kwargs['data-type'] = 'select2'
            kwargs['data-value'] = '1' if field.data else ''
            # data-source = dropdown options
            kwargs['data-source'] = json.dumps([
                {'value': '', 'text': gettext('No')},
                {'value': '1', 'text': gettext('Yes')}
            ])
            kwargs['data-role'] = 'x-editable-boolean'
        elif field.type in ['Select2Field', 'SelectField']:
            kwargs['data-type'] = 'select2'
            choices = [{'value': x, 'text': y} for x, y in field.choices]

            # prepend a blank field to choices if allow_blank = True
            if getattr(field, 'allow_blank', False):
                choices.insert(0, {'value': '__None', 'text': ''})

            # json.dumps fixes issue with unicode strings not loading correctly
            kwargs['data-source'] = json.dumps(choices)
        elif field.type == 'DateField':
            kwargs['data-type'] = 'combodate'
            kwargs['data-format'] = 'YYYY-MM-DD'
            kwargs['data-template'] = 'YYYY-MM-DD'
        elif field.type == 'DateTimeField':
            kwargs['data-type'] = 'combodate'
            kwargs['data-format'] = 'YYYY-MM-DD HH:mm:ss'
            kwargs['data-template'] = 'YYYY-MM-DD  HH:mm:ss'
            # x-editable-combodate uses 1 minute increments
            kwargs['data-role'] = 'x-editable-combodate'
        elif field.type == 'TimeField':
            kwargs['data-type'] = 'combodate'
            kwargs['data-format'] = 'HH:mm:ss'
            kwargs['data-template'] = 'HH:mm:ss'
            kwargs['data-role'] = 'x-editable-combodate'
        elif field.type == 'IntegerField':
            kwargs['data-type'] = 'number'
        elif field.type in ['FloatField', 'DecimalField']:
            kwargs['data-type'] = 'number'
            kwargs['data-step'] = 'any'
        elif field.type in ['QuerySelectField', 'ModelSelectField',
                            'QuerySelectMultipleField', 'KeyPropertyField']:
            # QuerySelectField and ModelSelectField are for relations
            kwargs['data-type'] = 'select2'

            choices = []
            selected_ids = []
            for value, label, selected in field.iter_choices():
                try:
                    label = text_type(label)
                except TypeError:
                    # unable to display text value
                    label = ''
                choices.append({'value': text_type(value), 'text': label})
                if selected:
                    selected_ids.append(value)

            # blank field is already included if allow_blank
            kwargs['data-source'] = json.dumps(choices)

            if field.type == 'QuerySelectMultipleField':
                kwargs['data-role'] = 'x-editable-select2-multiple'

                # must use id instead of text or prefilled values won't work
                separator = getattr(field, 'separator', ',')
                kwargs['data-value'] = separator.join(selected_ids)
            else:
                kwargs['data-value'] = text_type(selected_ids[0])
        else:
            raise Exception('Unsupported field type: %s' % (type(field),))

        return kwargs
Example #29
0
def get_pk_from_identity(obj):
    # TODO: Remove me
    key = identity_key(instance=obj)[1]
    return u":".join(text_type(x) for x in key)
Example #30
0
    def get_kwargs(self, subfield, kwargs):
        """
            Return extra kwargs based on the subfield type.
        """
        if subfield.type == 'StringField':
            kwargs['data-type'] = 'text'
        elif subfield.type == 'TextAreaField':
            kwargs['data-type'] = 'textarea'
            kwargs['data-rows'] = '5'
        elif subfield.type == 'BooleanField':
            kwargs['data-type'] = 'select'
            # data-source = dropdown options
            kwargs['data-source'] = {'': 'False', '1': 'True'}
            kwargs['data-role'] = 'x-editable-boolean'
        elif subfield.type == 'Select2Field':
            kwargs['data-type'] = 'select'
            choices = [{'value': x, 'text': y} for x, y in subfield.choices]

            # prepend a blank field to choices if allow_blank = True
            if getattr(subfield, 'allow_blank', False):
                choices.insert(0, {'value': '__None', 'text': ''})

            # json.dumps fixes issue with unicode strings not loading correctly
            kwargs['data-source'] = json.dumps(choices)
        elif subfield.type == 'DateField':
            kwargs['data-type'] = 'combodate'
            kwargs['data-format'] = 'YYYY-MM-DD'
            kwargs['data-template'] = 'YYYY-MM-DD'
        elif subfield.type == 'DateTimeField':
            kwargs['data-type'] = 'combodate'
            kwargs['data-format'] = 'YYYY-MM-DD HH:mm:ss'
            kwargs['data-template'] = 'YYYY-MM-DD  HH:mm:ss'
            # x-editable-combodate uses 1 minute increments
            kwargs['data-role'] = 'x-editable-combodate'
        elif subfield.type == 'TimeField':
            kwargs['data-type'] = 'combodate'
            kwargs['data-format'] = 'HH:mm:ss'
            kwargs['data-template'] = 'HH:mm:ss'
            kwargs['data-role'] = 'x-editable-combodate'
        elif subfield.type == 'IntegerField':
            kwargs['data-type'] = 'number'
        elif subfield.type in ['FloatField', 'DecimalField']:
            kwargs['data-type'] = 'number'
            kwargs['data-step'] = 'any'
        elif subfield.type in ['QuerySelectField', 'ModelSelectField']:
            # QuerySelectField and ModelSelectField are for relations
            kwargs['data-type'] = 'select'

            choices = []
            for choice in subfield:
                try:
                    choices.append({'value': text_type(choice._value()),
                                    'text': text_type(choice.label.text)})
                except TypeError:
                    # unable to display text value
                    choices.append({'value': text_type(choice._value()),
                                    'text': ''})

            # blank field is already included if allow_blank
            kwargs['data-source'] = json.dumps(choices)
        else:
            raise Exception('Unsupported field type: %s' % (type(subfield),))

        return kwargs
Example #31
0
def get_pk_from_identity(obj):
    # TODO: Remove me
    cls, key = identity_key(instance=obj)
    return u':'.join(text_type(x) for x in key)
def get_pk_from_identity(obj):
    res = identity_key(instance=obj)
    cls, key = res[0], res[1]
    return u':'.join(text_type(x) for x in key)
Example #33
0
    def get_kwargs(self, field, kwargs):
        """
            Return extra kwargs based on the field type.
        """
        if field.type == 'StringField':
            kwargs['data-type'] = 'text'
        elif field.type == 'TextAreaField':
            kwargs['data-type'] = 'textarea'
            kwargs['data-rows'] = '5'
        elif field.type == 'BooleanField':
            kwargs['data-type'] = 'select2'
            kwargs['data-value'] = '1' if field.data else ''
            # data-source = dropdown options
            kwargs['data-source'] = json.dumps([{
                'value': '',
                'text': gettext('No')
            }, {
                'value': '1',
                'text': gettext('Yes')
            }])
            kwargs['data-role'] = 'x-editable-boolean'
        elif field.type in ['Select2Field', 'SelectField']:
            kwargs['data-type'] = 'select2'
            choices = [{'value': x, 'text': y} for x, y in field.choices]

            # prepend a blank field to choices if allow_blank = True
            if getattr(field, 'allow_blank', False):
                choices.insert(0, {'value': '__None', 'text': ''})

            # json.dumps fixes issue with unicode strings not loading correctly
            kwargs['data-source'] = json.dumps(choices)
        elif field.type == 'DateField':
            kwargs['data-type'] = 'combodate'
            kwargs['data-format'] = 'YYYY-MM-DD'
            kwargs['data-template'] = 'YYYY-MM-DD'
            kwargs['data-role'] = 'x-editable-combodate'
        elif field.type == 'DateTimeField':
            kwargs['data-type'] = 'combodate'
            kwargs['data-format'] = 'YYYY-MM-DD HH:mm:ss'
            kwargs['data-template'] = 'YYYY-MM-DD  HH:mm:ss'
            # x-editable-combodate uses 1 minute increments
            kwargs['data-role'] = 'x-editable-combodate'
        elif field.type == 'TimeField':
            kwargs['data-type'] = 'combodate'
            kwargs['data-format'] = 'HH:mm:ss'
            kwargs['data-template'] = 'HH:mm:ss'
            kwargs['data-role'] = 'x-editable-combodate'
        elif field.type == 'IntegerField':
            kwargs['data-type'] = 'number'
        elif field.type in ['FloatField', 'DecimalField']:
            kwargs['data-type'] = 'number'
            kwargs['data-step'] = 'any'
        elif field.type in [
                'QuerySelectField', 'ModelSelectField',
                'QuerySelectMultipleField', 'KeyPropertyField'
        ]:
            # QuerySelectField and ModelSelectField are for relations
            kwargs['data-type'] = 'select2'

            choices = []
            selected_ids = []
            for value, label, selected in field.iter_choices():
                try:
                    label = text_type(label)
                except TypeError:
                    # unable to display text value
                    label = ''
                choices.append({'value': text_type(value), 'text': label})
                if selected:
                    selected_ids.append(value)

            # blank field is already included if allow_blank
            kwargs['data-source'] = json.dumps(choices)

            if field.type == 'QuerySelectMultipleField':
                kwargs['data-role'] = 'x-editable-select2-multiple'

                # must use id instead of text or prefilled values won't work
                separator = getattr(field, 'separator', ',')
                kwargs['data-value'] = separator.join(selected_ids)
            else:
                kwargs['data-value'] = text_type(selected_ids[0])
        else:
            raise Exception('Unsupported field type: %s' % (type(field), ))

        return kwargs
 def __str__(self):
     # return self.name
     return ', '.join(text_type(v) for v in self.name)
Example #35
0
 def _get_object_list(self):
     if self._object_list is None:
         query = self.query or self.query_factory()
         get_pk = self.get_pk
         self._object_list = [(text_type(get_pk(obj)), obj) for obj in query]
     return self._object_list
Example #36
0
    def get_kwargs(self, field, kwargs):
        """
            Return extra kwargs based on the field type.
        """
        if field.type == "StringField":
            kwargs["data-type"] = "text"
        elif field.type == "TextAreaField":
            kwargs["data-type"] = "textarea"
            kwargs["data-rows"] = "5"
        elif field.type == "BooleanField":
            kwargs["data-type"] = "select"
            # data-source = dropdown options
            kwargs["data-source"] = json.dumps(
                [{"value": "", "text": gettext("No")}, {"value": "1", "text": gettext("Yes")}]
            )
            kwargs["data-role"] = "x-editable-boolean"
        elif field.type in ["Select2Field", "SelectField"]:
            kwargs["data-type"] = "select"
            choices = [{"value": x, "text": y} for x, y in field.choices]

            # prepend a blank field to choices if allow_blank = True
            if getattr(field, "allow_blank", False):
                choices.insert(0, {"value": "__None", "text": ""})

            # json.dumps fixes issue with unicode strings not loading correctly
            kwargs["data-source"] = json.dumps(choices)
        elif field.type == "DateField":
            kwargs["data-type"] = "combodate"
            kwargs["data-format"] = "YYYY-MM-DD"
            kwargs["data-template"] = "YYYY-MM-DD"
        elif field.type == "DateTimeField":
            kwargs["data-type"] = "combodate"
            kwargs["data-format"] = "YYYY-MM-DD HH:mm:ss"
            kwargs["data-template"] = "YYYY-MM-DD  HH:mm:ss"
            # x-editable-combodate uses 1 minute increments
            kwargs["data-role"] = "x-editable-combodate"
        elif field.type == "TimeField":
            kwargs["data-type"] = "combodate"
            kwargs["data-format"] = "HH:mm:ss"
            kwargs["data-template"] = "HH:mm:ss"
            kwargs["data-role"] = "x-editable-combodate"
        elif field.type == "IntegerField":
            kwargs["data-type"] = "number"
        elif field.type in ["FloatField", "DecimalField"]:
            kwargs["data-type"] = "number"
            kwargs["data-step"] = "any"
        elif field.type in ["QuerySelectField", "ModelSelectField", "QuerySelectMultipleField", "KeyPropertyField"]:
            # QuerySelectField and ModelSelectField are for relations
            kwargs["data-type"] = "select"

            choices = []
            selected_ids = []
            for value, label, selected in field.iter_choices():
                try:
                    label = text_type(label)
                except TypeError:
                    # unable to display text value
                    label = ""
                choices.append({"value": text_type(value), "text": label})
                if selected:
                    selected_ids.append(value)

            # blank field is already included if allow_blank
            kwargs["data-source"] = json.dumps(choices)

            if field.type == "QuerySelectMultipleField":
                kwargs["data-type"] = "select2"
                kwargs["data-role"] = "x-editable-select2-multiple"

                # must use id instead of text or prefilled values won't work
                separator = getattr(field, "separator", ",")
                kwargs["data-value"] = separator.join(selected_ids)
        else:
            raise Exception("Unsupported field type: %s" % (type(field),))

        return kwargs