Exemplo n.º 1
0
class AuthPermissionView(ModelView):
    column_list = ('id', 'name', 'view_name')
    form_columns = (
        'name',
        'view_name',
    )
    form_extra_fields = {'view_name': Select2Field(_('View Name'))}
    form_widget_args = {
        'view_name': {
            'style': 'width:500px',
        }
    }
    column_labels = {
        'name': _('Name'),
        'id': _('ID'),
        'permissions': _('Permissions'),
        'view_name': _('View Name')
    }

    def get_query(self):
        return self.session.query(self.model).filter(self.model.name != 'ROOT')

    def get_count_query(self):
        return self.session.query(func.count('id')).select_from(
            self.model).filter(self.model.name != 'ROOT')

    def create_form(self, obj=None):
        form_class = super(AuthPermissionView, self).create_form()
        form_class.view_name.choices = get_endpoint_choices(
            self.admin.app, True)
        return form_class

    def edit_form(self, obj=None):
        form_class = super(AuthPermissionView, self).edit_form()
        if not form_class.name.data:
            form_class.name.data = obj.name
        form_class.view_name.choices = get_endpoint_choices(
            self.admin.app, True, obj.view_name)
        if not form_class.name.data:
            form_class.view_name.data = obj.view_name
        return form_class
Exemplo n.º 2
0
    def convert(self, model, mapper, prop, field_args, hidden_pk):
        # Properly handle forced fields
        if isinstance(prop, FieldPlaceholder):
            return form.recreate_field(prop.field)

        kwargs = {'validators': [], 'filters': []}

        if field_args:
            kwargs.update(field_args)

        # Check if it is relation or property
        if hasattr(prop, 'direction'):
            return self._convert_relation(prop, kwargs)
        else:
            # Ignore pk/fk
            if hasattr(prop, 'columns'):
                # Check if more than one column mapped to the property
                if len(prop.columns) != 1:
                    if is_inherited_primary_key(prop):
                        column = get_column_for_current_model(prop)
                    else:
                        raise TypeError(
                            'Can not convert multiple-column properties (%s.%s)'
                            % (model, prop.key))
                else:
                    # Grab column
                    column = prop.columns[0]

                form_columns = getattr(self.view, 'form_columns', None) or ()

                # Do not display foreign keys - use relations, except when explicitly instructed
                if column.foreign_keys and prop.key not in form_columns:
                    return None

                # Only display "real" columns
                if not isinstance(column, Column):
                    return None

                unique = False

                if column.primary_key:
                    if hidden_pk:
                        # If requested to add hidden field, show it
                        return fields.HiddenField()
                    else:
                        # By default, don't show primary keys either
                        # If PK is not explicitly allowed, ignore it
                        if prop.key not in form_columns:
                            return None

                        # Current Unique Validator does not work with multicolumns-pks
                        if not has_multiple_pks(model):
                            kwargs['validators'].append(
                                Unique(self.session, model, column))
                            unique = True

                # If field is unique, validate it
                if column.unique and not unique:
                    kwargs['validators'].append(
                        Unique(self.session, model, column))

                optional_types = getattr(self.view, 'form_optional_types',
                                         (Boolean, ))

                if not column.nullable and not isinstance(
                        column.type, optional_types):
                    kwargs['validators'].append(validators.InputRequired())

                # Apply label and description if it isn't inline form field
                if self.view.model == mapper.class_:
                    kwargs['label'] = self._get_label(prop.key, kwargs)
                    kwargs['description'] = self._get_description(
                        prop.key, kwargs)

                # Figure out default value
                default = getattr(column, 'default', None)
                value = None

                if default is not None:
                    value = getattr(default, 'arg', None)

                    if value is not None:
                        if getattr(default, 'is_callable', False):
                            value = lambda: default.arg(None)
                        else:
                            if not getattr(default, 'is_scalar', True):
                                value = None

                if value is not None:
                    kwargs['default'] = value

                # Check nullable
                if column.nullable:
                    kwargs['validators'].append(validators.Optional())

                # Override field type if necessary
                override = self._get_field_override(prop.key)
                if override:
                    return override(**kwargs)

                # Check choices
                form_choices = getattr(self.view, 'form_choices', None)

                if mapper.class_ == self.view.model and form_choices:
                    choices = form_choices.get(column.key)
                    if choices:
                        return Select2Field(choices=choices,
                                            allow_blank=column.nullable,
                                            **kwargs)

                # Run converter
                converter = self.get_converter(column)

                if converter is None:
                    return None

                return converter(model=model,
                                 mapper=mapper,
                                 prop=prop,
                                 column=column,
                                 field_args=kwargs)

        return None
Exemplo n.º 3
0
    def convert(self, model, mapper, prop, field_args, hidden_pk):
        kwargs = {
            'validators': [],
            'filters': []
        }

        if field_args:
            kwargs.update(field_args)

        # Check if it is relation or property
        if hasattr(prop, 'direction'):
            remote_model = prop.mapper.class_
            local_column = prop.local_remote_pairs[0][0]

            kwargs['label'] = self._get_label(prop.key, kwargs)
            kwargs['description'] = self._get_description(prop.key, kwargs)

            if local_column.nullable:
                kwargs['validators'].append(validators.Optional())
            elif prop.direction.name != 'MANYTOMANY':
                kwargs['validators'].append(validators.InputRequired())

            # Override field type if necessary
            override = self._get_field_override(prop.key)
            if override:
                return override(**kwargs)

            # Contribute model-related parameters
            if 'allow_blank' not in kwargs:
                kwargs['allow_blank'] = local_column.nullable
            if 'query_factory' not in kwargs:
                kwargs['query_factory'] = lambda: self.session.query(remote_model)

            if prop.direction.name == 'MANYTOONE':
                return QuerySelectField(widget=form.Select2Widget(),
                                        **kwargs)
            elif prop.direction.name == 'ONETOMANY':
                # Skip backrefs
                if not local_column.foreign_keys and getattr(self.view, 'column_hide_backrefs', False):
                    return None

                return QuerySelectMultipleField(
                                widget=form.Select2Widget(multiple=True),
                                **kwargs)
            elif prop.direction.name == 'MANYTOMANY':
                return QuerySelectMultipleField(
                                widget=form.Select2Widget(multiple=True),
                                **kwargs)
        else:
            # Ignore pk/fk
            if hasattr(prop, 'columns'):
                # Check if more than one column mapped to the property
                if len(prop.columns) != 1:
                    raise TypeError('Can not convert multiple-column properties (%s.%s)' % (model, prop.key))

                # Grab column
                column = prop.columns[0]

                # Do not display foreign keys - use relations
                if column.foreign_keys:
                    return None

                # Only display "real" columns
                if not isinstance(column, Column):
                    return None

                unique = False

                if column.primary_key:
                    if hidden_pk:
                        # If requested to add hidden field, show it
                        return fields.HiddenField()
                    else:
                        # By default, don't show primary keys either
                        form_columns = getattr(self.view, 'form_columns', None)

                        if form_columns is None:
                            return None

                        # If PK is not explicitly allowed, ignore it
                        if prop.key not in form_columns:
                            return None

                        kwargs['validators'].append(Unique(self.session,
                                                           model,
                                                           column))
                        unique = True

                # If field is unique, validate it
                if column.unique and not unique:
                    kwargs['validators'].append(Unique(self.session,
                                                       model,
                                                       column))

                if not column.nullable and not isinstance(column.type, Boolean):
                    kwargs['validators'].append(validators.InputRequired())

                # Apply label and description if it isn't inline form field
                if self.view.model == mapper.class_:
                    kwargs['label'] = self._get_label(prop.key, kwargs)
                    kwargs['description'] = self._get_description(prop.key, kwargs)

                # Figure out default value
                default = getattr(column, 'default', None)
                value = None

                if default is not None:
                    value = getattr(default, 'arg', None)

                    if value is not None:
                        if getattr(default, 'is_callable', False):
                            value = lambda: default.arg(None)
                        else:
                            if not getattr(default, 'is_scalar', True):
                                value = None

                if value is not None:
                    kwargs['default'] = value

                # Check nullable
                if column.nullable:
                    kwargs['validators'].append(validators.Optional())

                # Override field type if necessary
                override = self._get_field_override(prop.key)
                if override:
                    return override(**kwargs)

                # Check choices
                if mapper.class_ == self.view.model and self.view.form_choices:
                    choices = self.view.form_choices.get(column.key)
                    if choices:
                        return Select2Field(
                            choices=choices,
                            allow_blank=column.nullable,
                            **kwargs
                        )

                # Run converter
                converter = self.get_converter(column)

                if converter is None:
                    return None

                return converter(model=model, mapper=mapper, prop=prop,
                                column=column, field_args=kwargs)

        return None